JavaScript: About the collection and efficiency in JavaScript, Javascript tutorial
An array is an internal object provided by JavaScript. It is a standard set. We can add (push), delete (shift) elements, we can also traverse the elements in the for loop, so can we have other sets in addition to arrays in JavaScript?
Because of the language features of JavaScript, We can dynamically add and delete attributes to common objects. Therefore, objects can also be seen as a special set of JS. The following compares the features of Array and Object:
Array:
New: var ary = new Array (); or var ary = [];
Added: 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 = {};
Added: obj [key] = value; (key is string)
Delete: delete obj [key];
Traversal: for (var key in obj) obj [key];
From the above comparison, we can see that the Object can be used as a set.Use the Popup window to create an infinitely webpage menu (3)The _ MenuCache __implemented by Eric is a simulated set object.
If we want to retrieve a specified value in Array, We need to traverse the entire Array:
Var Keyword = ;
For ( Var I = 0 ; I < Ary. length; ++ I)
{
If (Ary [I] = Keyword)
{
// Todo
}
}
However, to retrieve a specified key entry in an Object, you only need to use:
Var Key = '';
Var Value = Obj [key];
// Todo
This feature of the Object can be used to efficiently retrieve the string set of Unique. The time complexity of traversing the Array is O (n), and the time complexity of traversing the Object is O (1 ). Although the for search cost for 10000 sets is dozens of ms, if it is 1000*1000 queries or more, the advantages of using objects are shown. Before that, I made a mapping to map 100 Unique characters to 1000 string arrays, which took 25-30 s! Later, I changed the for traversal to the member reference of the Object simulation set. The same data volume mapping takes only 1.7-2 s !!!
For the collection traversal efficiency (from high to low ):VarValue=Obj [key];> for (;)> for (in ). The worst efficiency is for (in). If the set is too large, do not use for (in) traversal.
Original article:Http://www.cnblogs.com/birdshome/archive/2005/01/05/87009.html