Efficiency comparison of three JavaScript array searches

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.