JavaScript: difference in performance of indexOf method for String and Array

I am curious if there is a difference in performance for a method indexOfavailable for both Array, and Stringin JavaScript. I thought it was indexOfless 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';

//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 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');
+4
1

, indexOf, , , .

indexOf , , , "item1, item2".

http://jsperf.com/indexof-array-vs-string-efficiency

jsperf , , indexOf , , indexOf .

* , String indexOf , , indexOf ( "ocean" ) true, , blueocean, , , indexOf ( ", ocean" )/p >

+2

Source: https://habr.com/ru/post/1611050/


All Articles