Suppose I have an array of strings, and I want to find the index of a given string in that array. I'm wondering whether there will be much of a performance difference between these two functions:
func indexOfName(name: String) -> Int? {
for (index, element) in names.enumerate() {
if element == name {
return index
}
}
return nil
}func indexOfName(name: String) -> Int? {
return names.enumerate().filter { $0.element == name }.first?.index
}Or is the difference between them simply one of notation?
There'll be some performance difference, in general, because the second one creates an array to hold the results, which means it likely has to allocate memory.
However, you should be using the standard 'indexOf' method (Swift 2) or 'index (of:)' (Swift 3). That way you can take advantage of any optimizations built into the standard library.