1. Background
When writing JS, there is often a need to query for a value in a string array, which can be used for in or for i++ or directly arr.join (', '). IndexOf () Three ways: The last type of code is the least so to use, but how efficient is not self-assured. So I'm going to test it today.
2. Test code
Constructs an array var arr=[];for (var i=0;i<=1000000;i++) {Arr.push (' Abcdefghigk ' +i);} var v= ' abcdefghigk1000000 ';//The value to be compared is the last Console.log (' for in '),//for in way query Console.time (' arr '); var find =false;for ( var i in arr) {if (arr[i]===v) {find=true;break;}} Console.log (find); Console.timeend (' arr '); Console.log (' for i++ ');//for i++ Way Query Console.time (' arr '); var find =false; for (Var i=0,len=arr.length;i<len;i++) {if (arr[i]===v) {find=true;break;}} Console.log (find); Console.timeend (' arr '); Console.log (' string ');//join way Query Console.time (' arr '); Console.log (', ' + Arr.join (', ') + ', '). IndexOf (', ' +v+ ', ')); Console.timeend (' arr ');
3. Test results
Run directly on the chrome console to see the results
4. Summary
The results of this test are at a glance.
String>>for in>for i++
The normal for loop is slightly slower than for-in, and the more likely the internal runtime does, the more efficient it is. Join and IndexOf are built-in methods, so the speed is particularly fast.
Efficiency comparison of three JavaScript array searches