Reputation: 109
Let's say we need to check 1m users, how should it be done?
for (var i = 0;i<1000000;i++){
users[i].abc();
users[i].abc2();
}
or
for (var i = 0;i<1000000;i++){
var user = users[i];
user.abc();
user.abc2();
}
Which one would be faster and why?
Upvotes: 1
Views: 123
Reputation: 4972
According to https://en.wikipedia.org/wiki/Chrome_V8 the v8 compiler will compile your code to native machine code.
Depending of the optimizations made by the compiler, you have no precise way to guarantee which version will be faster.
As pointed out in other answers, the difference, if any, will not be relevant.
The compiled code is additionally optimized (and re-optimized) dynamically at runtime, based on heuristics of the code's execution profile. Optimization techniques used include inlining, elision of expensive runtime properties, and inline caching, among many others.
So, the points to take in consideration for your case are not based on execution speed.
I would say that if you run a lot of users[i]
then dereferencing to a local user
variable is ok, because on the long run it saves you characters to type ("s[i]"
)
If you run only one or two users[i]
then stay with that because dereferencing will only use more line codes.
In short, I would opt for the code which is the more compact.
UPDATE:
I tried @Alexander Elgin code and it shows huge differences on local execution from 50% to 20% speed gain, so it is not 'irrelevant' as I or others stated (+1 for him)
But, I stand on the idea that it all depends of the optimizations performed by the execution engine, but indeed on my nodejs version, the dereferencing seems to be a lot faster on huge loops.
Upvotes: 0
Reputation: 6965
The second loop is about 20%-30% faster. See the results of the snippet below. I.e. creation of a reference takes less time than addressing by index in an array.
var users = [];
for (var i = 0;i<1000000;i++){
users.push({abc: function() {}, abc2: function() {}});
}
var now = new Date();
for (var i = 0;i<1000000;i++){
users[i].abc();
users[i].abc2();
}
console.log('The first loop requires ' + (new Date().getTime() - now.getTime()) + 'ms');
now = new Date();
for (var i = 0;i<1000000;i++){
var user = users[i];
user.abc();
user.abc2();
}
console.log('The second loop requires ' + (new Date().getTime() - now.getTime()) + 'ms');
Upvotes: 1
Reputation: 16693
Loop version 1 will run slower but will take less memory usage. The reason is that it accesses your array with the iterator i
2 times per loop iteration.
Loop version 2 will run faster but will consume more memory. The reason is that it accesses the array only once per loop iteration, but creates a variable instance (user
).
Having said that, both versions are very similar and all performance / memory usage differences are basically insignificant.
Upvotes: 0