var name = function(n) {
var digits = [\'one\',\'two\',\'three\',\'four\'];
return digits[n];
}
var namenew = (function() {
digits = [\'one\',\'two\',\'thre
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.