I'm trying to understand how the get item at index works in an array in JavaScript.
For example imagine I have a for iterating an array with thousands (or millions) of items. Which would be the best way (with the best performance) to print the items?
// Option 1
for (int i = 0; i < array.length; i++) {
var data = array[i];
console.log( data.ID, data.name, data.date, data.description );
}
// Option 2
for (int i = 0; i < array.length; i++) {
console.log( array[i].ID, array[i].name, array[i].date, array[i].description );
}
Is it option 1 or option 2? Or is it the same thing to use the first or second option? Or is there an even better way to do this?
I know for instance that get() in the Java ArrayList works this way, so obviously the best approach would be option 1, since it checks the range each time it calls the get() method.
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
Does JavaScript works in a similar way?
The "big question" here is really how does JavaScript array get item at index works
Note: I've tried to search for the best way to get an element in an array, but all I could find was the best way to iterate an Array. That isn't what I'm trying to get from this question!
EDIT
Forget everything I've said. It was true for very old browsers. For the new ones (tested with Chrome, Firefox, IE11 and Edge), there is almost no difference between any of those examples.
I've tested with an array of 100 million records, and the difference is < 1ms.
The Option 2 apparently is slightly faster, nothing that will really count.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With