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


i curious whether there exists difference in efficiency indexof method available both array , string in javascript. thought indexof less efficient on string on array, , new testing results support this. example:

var arr = ['abc', 'ab', 'abz', '1'];  var str = 'abcababz1';  var needle = 'abxx';  //concatenate make them bigger (var = 0; < 30; i++) {     arr = arr.concat(arr);     str = str.concat(str); } arr.push(needle);  //append needle last str = str.concat(needle); 

then used start , end timestamp

arr.indexof(needle); // faster! str.indexof(needle);  

i did testing in node, new testing results showed:

time used on array is: 35 time used on string is: 57 

so array more efficient indexof string. new testing creates worst case scenario -- needle @ end of string or array.

edit:

if indexof more efficient on array, wondering if should first split string (delimited comma, example) array before using indexof method search sub string.

for string:

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

if search ocean, first split string str2 array use indexof find ocean?

var arr2 = str2.split(","); arr2.indexof('ocean'); 

i'm guessing based on edit want use indexof check if given element exists in list starts string.

the 2 options using indexof on string or parsing array first , seeing if element exists there, since know format "item1,item2".

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

based on jsperf can see though indexof faster on array itself, converting string array has cost , you're better off doing indexof on raw string.

*note string indexof need additional modification make sure indexof("ocean") doesn't return true if have element blueocean, , instead want indexof(",ocean,")


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -