I am curious if there is a difference in performance for a method indexOf
available for both Array
, and String
in JavaScript. I thought it was indexOf
less efficient for String than for Array, and my new test results support this. For example:
var arr = ['abc', 'ab', 'abz', '1'];
var str = 'abcababz1';
var needle = 'abxx';
for (var i = 0; i < 30; i++) {
arr = arr.concat(arr);
str = str.concat(str);
}
arr.push(needle);
str = str.concat(needle);
Then I used the start and end timestamp for
arr.indexOf(needle);
str.indexOf(needle);
I did this testing in node, the results of a new test showed:
time used on Array is: 35
time used on String is: 57
So, an array is more efficient for indexOf than String. This new test basically creates the worst case scenario - a needle at the very end of a string or array.
Edit:
indexOf
Array, , String ( , ) , indexOf
.
:
var str2 = "hello,world,country,continent,ocean"
ocean
, str2
, indexOf
, ocean
?
var arr2 = str2.split(",");
arr2.indexOf('ocean');