4 ms·
It does not specify a vm or version. I assume it's v8 on node, but there's no way to infer what version was used. If using node, use process.hrtime() rather th
by partycoder 8y ago
It does not specify a vm or version. I assume it's v8 on node, but there's no way to infer what version was used.
If using node, use process.hrtime() rather than console.time()/timeEnd():
https://nodejs.org/api/process.html#process_process_hrtime_time https://nodejs.org/api/process.html#process_process_hrtime_t...
Then, computing the length multiple times is not a good idea. You should save the length in a variable:
// no
for(let i=0; i<posts.length; i++) {
// yes
for(let i=0, n=posts.length; i<n; i++) {
Finally, it is not recommended to analyze performance in this manner. A slight little change elsewhere in your program can affect the performance very abruptly.
This is because the gatekeepers of performance are: inline caching, hidden classes, deoptimizations, garbage collection, pretenuring, etc.
- ryanpetrich 8y agoCaching the length property appears to have only a small impact on performance across Chrome, Firefox and Safari (caching is faster in Firefox, slower in Chrome, and about the same in Safari). Perhaps it's better to recommend the non-cached loop iteration instead? The quick microbenchmark I checked this on: https://jsperf.com/for-to-length/1 https://jsperf.com/for-to-length/1
- fenomas 8y ago// yes for(let i=0, n=posts.length; i<n; i++) { There's usually no need to cache the length of the array this way. Modern JS VMs are plenty smart enough to do it automatically (unless there's code in the loop that looks like it might change the array length).
- denomer 8y agoThanks :) Working on it.
- masswerk 8y agoWhile caching the array.length had been important, it probably does little with modern engines. I remember tests from a few years ago, which actually favored the first variant. (Probably, because engines could more easily identify the local context and optimize on this. Also, in terms of runtime optimization, there's much to win and you'd want to tackle this issue as one of the very first things.) That said, it's still a good idea, even if it's just for pointing out that the constraint on the loop won't change.
- denomer 8y agoSo, after working on this for some time and reading a lot, i realized that this example is more of a practical analysis for day today js code writing that we do. so the result is more kind of related to it and what should be the choice from those 3. However, you are right about the performance benchmarking factor. Good news, I have done analysis on the inline cache, warm cache and working on how to get GC in place and hidden classes to get better results.