Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Micro optimization, is it optimized anyway by modern browsers?

I inherited a library recently, there is an update method which exists on a class. Here is an example.

onPointerMove(pointer, x, y, isPressed){
    var floor = Math.floor;
    var cx = this.currentX;
    var cy = this.currentY;
    var tm = this.toolManager; 
}

This kind of code mostly only exists on performance critical stuff. Most of the rest of the project is not written this way.

  1. Floor is used twice. Surely caching it in a local variable simply forces some "temporary" memory allocation every time it is run? How is that faster than simply looking up a function?
  2. This.currentX is referenced many times during the body of the function but is caching it really any faster? I would have thought that this.currentX involves no lookup issues but maybe I am wrong. Since this is happening to the remaining code in the example, all of these properties are cached.

Does any of this really matter at all any more on modern JavaScript engines? I would assume that the optimizations such as this, if they are faster.... Would be taken as a given for optimization anyway inside V8. For example if Math.round was called 20 times in a function, then the engine would cache it anyway?

I would also expect stuff like caching a length before you "for it" is also another example of what I presume optimised engines to do anyway when interpreting the code (again, only IF it even makes a difference).

All I really want to know is... from this day forward, should I be doing these Micro-Optimisations (for evergreen browsers) and optimizing my code or have things moved on a little now since 2010 (when I read Performance JavaScript)

Thanks!

like image 555
Clark Avatar asked Oct 19 '22 17:10

Clark


1 Answers

Don't optimize prematurely. Unless some profiling shows that these things in the code actually cause some sort of bottleneck, or disproportionate resource use, don't bother optimizing them along theories on performance.

As for the actual performance: object attribute lookups (such as Math.floor or this.currentX) are o(1) operations, as they are effectively hashmap lookups. Saving them to a variable as such looks like more of a readability enhancement than anything.

like image 92
doldt Avatar answered Oct 27 '22 11:10

doldt