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!
str.indexOf(needle);
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.
Edit:
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(",");
arr2.indexOf('ocean');
indexOf
methods' algorithms and implementations. It's not one single function applied to two data structures, they are two very different functions. So, what's the point of this question? – Ortrud