Created
October 11, 2015 12:13
-
-
Save v3rt1go/d77360f669cf06eb6326 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using closures for performance gains | |
// 1. This is bad because we assign names on the global scope | |
// and it might impact with other vars with same name in global | |
var names = ['zero', 'one', 'two', 'three', 'four', 'five']; | |
var digit_names = function(n) { | |
return names[n] | |
}; | |
console.log(digit_names(1)); | |
// 2. This is better but it's slow because we initialized names each | |
// time the function is called | |
var scope_digit_names = function(n) { | |
var names2 = ['zero', 'one', 'two', 'three', 'four', 'five']; | |
return names2[n]; | |
}; | |
console.log(scope_digit_names(2)); | |
// We wrap the function in an iife and define names inside. We return | |
// just the function that reads the index name. The function that is returned | |
// has access to the scope of the parent, even though it returned and names | |
// is persisted in memory | |
var closure_digit_names = (function() { | |
var names3 = ['zero', 'one', 'two', 'three', 'four', 'five']; | |
return function(n) { | |
return names3[n]; | |
} | |
}()); | |
console.log(closure_digit_names(3)); | |
// The method above immediatly executes the parent function and loads names in memory | |
// giving access to it to the returned child function, that gets assigned to the var | |
// names. | |
// This can be further optimized, to avoid paying the cost of initializing names array | |
// if we never call the function (avoid paying the cost of the iife) by lazy loading | |
// the names var | |
var lazy_digit_names = (function() { | |
var names4; | |
return function(n) { | |
if (!names4) { | |
names4 = ['zero', 'one', 'two', 'three', 'four', 'five']; | |
} | |
return names4[n]; | |
}; | |
})(); | |
console.log(lazy_digit_names(4)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment