Javascript performance with closure

后端 未结 2 1160
广开言路
广开言路 2021-02-01 23:02
var name = function(n) {
    var digits = [\'one\',\'two\',\'three\',\'four\'];
    return digits[n];
}

var namenew = (function() {
    digits = [\'one\',\'two\',\'thre         


        
2条回答
  •  [愿得一人]
    2021-02-01 23:45

    The first function recreates digits every time it's executed. If it's a large array this is needlessly expensive.

    The second function stores digits in a context shared only with namenew. Every time namenew is executed it only performs a single operation: return digits[n].

    An example like this wont show any noticeable gains in performance, but with very large arrays/objects/function calls performance will be improved significantly.

    In an OOP perspective using a closure in this manner is similar to storing data in a static variable.


    Don't forget that namenew is receiving the result of the closure function. The closure itself is only executed once.

提交回复
热议问题