JavaScript: difference in efficiency of indexOf method on String and Array

I am curious whether there exists a difference in efficiency for the indexOf method that is available for both Array and String in JavaScript. I thought the indexOf is less efficient on String than on Array, and my new testing results support this. For example:

var arr = ['abc', 'ab', 'abz', '1'];

var str = 'abcababz1';

var needle = 'abxx';

//concatenate to make them bigger
for (var i = 0; i < 30; i++) {
    arr = arr.concat(arr);
    str = str.concat(str);
arr.push(needle);  //append needle last
str = str.concat(needle);

Then I used the start and end timestamp for

arr.indexOf(needle); // faster!

I did this testing in node, the new testing results showed:

time used on Array is: 35
time used on String is: 57

So the Array is more efficient for indexOf than String. This new testing basically creates the worst case scenario -- needle at the very end of String or Array.


If the indexOf is more efficient on Array, I was wondering if we should first split a String (delimited by comma, for example) to an array before using the indexOf method to search for a sub string.

For this string:

var str2 = "hello,world,country,continent,ocean"

If you search for ocean, would you first split the string str2 to an array then use indexOf to find ocean?

var arr2 = str2.split(",");



I'm guessing based on your edit that you want to use indexOf to check if a given element exists in your list that starts as a string.

The two options then are using indexOf on the string itself or parsing it to an array first and seeing if the element exists there, since you know the format is "item1,item2".

Based on that jsperf we can see that even though indexOf is faster on the array itself, converting the string to an array has a cost to it as well and you're better off doing the indexOf on the raw string.

*Note that the String indexOf would need some additional modification to make sure indexOf("ocean") doesn't return true if you have an element like blueocean, and would probably instead want indexOf(",ocean,")


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.