JavaScript Performance: Multiple variables or one object?

后端 未结 4 671
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 02:47

this is just a simple performance question, helping me understand the javascript engine. for this I\'m was wondering, what is faster: declaring multiple variables for certai

4条回答
  •  执念已碎
    2020-12-09 03:17

    Theory or questions like "What you are ..hmm.. doing, dude?", of course, can appear here as an answers. But I dont think it's good approach.

    I just created two test benchs:


    1. Specific, http://jsben.ch/SvNyw for global scope

    It shows, for example, that on 07/2017 in Chromium based browsers (Vivaldi, Opera, Google Chrome and other) to achieve max performance there are preferable to use var. It works about 25% faster for reading values and 10% faster for writing ones.

    Under Node.js there're about the same results - because of same JS engine.

    In Opera Presto (12.18) there're the similar percentage test results as in chromium-based browsers.

    In (modern) Firefox there is other and strange picture. Reading of global scope var is around the same as reading of object property, and writing of global scope var is dramatically slower than writing obj.prop (around twice slower). It seems like a bug.

    For testing under IE/Edge or any others you are welcome.


    1. Normal case, http://jsben.ch/5UvSZ for in-function local scope

    In both Chromium based browsers and Mozilla Firefox you can see huge domination of simple var performance according to object property access. Local simple variables are several times (!) faster than dealing with object properties.


    So,

    if you need maximize some critical JavaScript code performance:

    • in browser - you can forced to make different optimizations for several browsers. I dont recommend! Or you can select some "favorite" browser, optimize your code for it and do not see what freezes happens in other ones. Not wery good, but is the way.

    • in browser, again - do you really need to optimize this way? May be something wrong in your algorithm / code logic?

    • in highload Node.js module (or other highload calcs) - well, try to minimize object "dots", with minimized damage to quality/readability of course - use var.

    The safe optimization trick for any case - when you have too much operations with obj.subobj.* you can do var subobj = obj.subobj; and operate with subobj.*. This can ever improve readability.

    In any case, think what do you need and do and make real bechmarks of you highload code.

提交回复
热议问题