Dave G Dave G - 9 months ago 44
Swift Question

Contains or for-loop, what's more efficient?

Using Swift, I have an array of about 30 strings (each string is a single word). I also have a variable string and I want to check if the string has a matching value in the array.

My question is, from an efficiency standpoint, should I just use:

if myArray.contains("MyString") {
//Do stuff

Or should I loop through it?

for i in 0..<myArray.count {
if myArray[i] == "MyString" {
//Do stuff

Answer Source

From an efficiency standpoint it is more efficient to use myArray.contains("myString") since it will stop once it reaches value equal to "myString" , if it does exist in the array at all. A for-loop will continue through all the values even after it finds the value you have specified so it is less efficient but probably only offers a negligible efficiency upgrade.

Like @vadian said there is a 3rd way. An there is also a 4th way, using a while-loop, which you could make stop after the value you have searched for is found, however using .contains(...) is far more readable and concise and thus in my opinion is the best choice.