0

Lets say I have a string of fruit names

var string = "cherries,oranges,limes"

and an array of red fruit

var array = ["tomatoes", "cherries", "raspberries"]

in javascript if I want to find if the string has any red fruit, I can do

for(var i=0; i<array.length; i+=1){
    if(string.search(array[i])!=-1){
        return string.search(array[i]);

}

How would this compare with the following?

var string_array= string.split(','); 
for(var i=0; i<array.length; i+=1){
    for(var j=0; j<string_array.length; j+=1){
       if(string_array[j]==array[i]){
       return string_array[j];
       }
}
}
return -1;
2
  • What do you mean "How would this compare" ? You'd like to know what speed difference you'd observe using Chrome's profiler or jsperf ? Commented Jul 17, 2012 at 18:26
  • Yes, I meant performance-wise. Commented Jul 18, 2012 at 18:52

1 Answer 1

1

This can't work ;

for(var i=0; i<array.length; i+=1){
   return string.search(array[i]);
}

You're returning at your first iteration.

So, this wouldn't compare very well.

BTW, if you're interested in script performance comparisons, I suggest you to try using jsperf.

Sign up to request clarification or add additional context in comments.

1 Comment

Woops, missed that. Fixed above. Thanks for the recommendation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.