3 ms·
In cases where order doesn't matter you can avoid you can avoid the array length question all together by decrementing: let index = arr.length; do {
by austincheney 6y ago
In cases where order doesn't matter you can avoid you can avoid the array length question all together by decrementing:
let index = arr.length;
do {
index -= 1;
console.log(arr[index]);
} while (index > 0);
As a side note whether it takes longer to access a variable or object property is largely superficial depending upon the size of object because it implies creating a new variable on which to store that object property. There is time involved to invoke a new variable just as there is time involved to access an object's property.
As an added bit of trivia in the 1970s a software developer named Paul Heckel, known for Heckel Diff algorithm, discovered that access to object properties is faster than accessing array indexes half the time. That was in C language, but it holds true in JavaScript.
- nostrademons 6y agoIn 2009 we standardized on this form for all Google Search JS for-each loops, because we were literally counting bytes on the SRP: for(var i=0,e;e=a[i++];){ ... } Could result in problems if the array contained falsey values, but we just didn't do that. Nowadays, like I mentioned above, I'd just do arr.foreach((elem, i) => { ... }); Which last time I checked was significantly slower than the for-loop, but I've learned my lesson about trying to optimize for browser quirks that may disappear in a year or two. :-)
- layoutIfNeeded 6y ago>[...] discovered that access to object properties is faster than accessing array indexes half the time. That was in C language, but it holds true in JavaScript. What are these object properties in C?
- austincheney 6y agoHash map then.
- layoutIfNeeded 6y agoHm. So you're saying that indexing into a hash map can be faster than indexing into an array? How would this be possible? I mean, under the hood a hash map is going to an array too, which is being indexed based on the hash value...
- austincheney 6y agoHash map properties are randomly accessed from memory opposed to array indexes.