Home > Web Front-end > JS Tutorial > Talk about arrays, collections and efficiency in JavaScript_Javascript tutorial

Talk about arrays, collections and efficiency in JavaScript_Javascript tutorial

黄舟
Release: 2016-12-20 15:12:11
Original
829 people have browsed it

Array is an internal object provided by JavaScript. It is a standard collection. We can add (push) and delete (shift) the elements in it. We can also traverse the elements in it through a for loop. In addition to the array, we also have Can there be other collections?


Due to the language features of JavaScript, we can dynamically add and delete properties to general objects. So Object can also be regarded as a special collection of JS. Let’s compare the characteristics of Array and Object:

 Array:

New: var ary = new Array(); or var ary = [];

Add: ary.push(value);

Delete: delete ary[ n];

Traversal: for ( var i=0 ; i < ary.length ; ++i ) ary[i];

 Object:

New: var obj = new Object(); or var obj = {};

Add: obj[key] = value; (key is string)

Delete: delete obj[key];

Traverse: for (var key in obj) obj[key];

 From above From the comparison, we can see that Object can be used as a collection. In using the Popup window to create an infinite Web page menu (3), I introduced the __MenuCache__ implemented by Eric, which is also a simulated collection object.

 If we want to retrieve a specified value in Array, we need to traverse the entire array:

ebf969465e22595a9eff9ac99a99bbbe

Object It can be used to efficiently retrieve Unique string collections. The time complexity of traversing Array is O(n), while the time complexity of traversing Object is O(1). Although the cost of for retrieval for 10,000 collections is only tens of ms, if it is 1,000*1,000 retrievals or more, the advantages of using Object will be immediately apparent. Before that, I did a mapping, mapping 100 Unique characters to 1000 string arrays, which took 25-30 seconds! Later, I changed the for traversal to the member reference of the Object simulated collection, and the same amount of data was mapped , it takes only 1.7-2s!!!

 For the traversal efficiency of the collection (from high to low): var value = obj[key]; > for ( ; ; ) > for ( in ). The least efficient one is for(in). If the collection is too large, try not to use for(in) to traverse.


The above is the content of the Javascript tutorial about arrays, collections and efficiency in JavaScript. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template