Temporary complexity javascript.length

What is the time complexity of the javascript.length array? I think it will be permanent, since it seems that the property is set automatically on all arrays, and you just look at it?

+6
source share
2 answers

I think it will be permanent, since it seems that the property is set automatically on all arrays, and you just look at it?

Right Probably. This is a property that is stored (not evaluated) and is automatically updated as needed.

Having said that, remember that JavaScript engines can do what they like on the covers if you cannot observe any deviation from what the spec says. Since the specification says nothing about the time complexity of length ...

Also remember that standard JavaScript classes are, in theory, just objects with special behavior . And, theoretically, JavaScript objects are property bags. Thus, the search for a property in a property bag theoretically depends on how many other properties exist if the object is implemented as a kind of hashmap value-name (and they were before, in the good old days). Modern engines optimize objects (Chrome V8 famously creates dynamic classes on the fly and compiles them), but operations on these objects can still change the performance of property searches. Adding a property can cause V8 to subclass, for example. Removing a property (actually using delete ) can cause V8 to crack its hands and return to "dictionary mode", which significantly impairs access to the object on the object.

In other words: it can vary, engine to engine, even an object for an object. But if you use arrays exclusively as arrays (without storing other non-array properties on them), the likelihood that you will get a constant search.

+7
source

This doesn't seem like a bottleneck, but if you want to be sure to use var len = arr.length and check it out. This will not hurt and seems to be a little faster on my car, although it does not make a significant difference.

 var arr = []; for (var i = 0; i < 1000000; i++) { arr[i] = Math.random(); } var start = new Date(); for (var i = 0; i < arr.length; i++) { arr[i] = Math.random(); } var time1 = new Date() - start; var start = new Date(); for (var i = 0, len = arr.length; i < len; i++) { arr[i] = Math.random(); } var time2 = new Date() - start; document.getElementById("output").innerHTML = ".length: " + time1 + "<br/>\nvar len: " + time2; 
 <div id="output"></div> 
+1
source

All Articles