Skip to content

Instantly share code, notes, and snippets.

@ardalanamini
Created February 24, 2018 20:22
Show Gist options
  • Save ardalanamini/64511a757156a9eee3389d39e72ef939 to your computer and use it in GitHub Desktop.
Save ardalanamini/64511a757156a9eee3389d39e72ef939 to your computer and use it in GitHub Desktop.
'let' vs 'var' performance. just run the code below to see the magic
/**
* Finds the performance for a given function
* function fn the function to be executed
* int n the amount of times to repeat
* return array [time for n iterations, average execution frequency (executions per second)]
*/
const getPerf = (fn, n) =>{
let start = new Date().getTime()
for (let i = 0; i < n; i++) fn(i)
let end = new Date().getTime()
return [parseFloat((end - start).toFixed(3)), parseFloat((repeat * 1000 / (end - start)).toFixed(3))]
}
let repeat = 100000000
//-------inside a scope------------
let letperf1 = getPerf(function(i) {
if (true) {
let a = i
}
}, repeat)
console.log(`'let' inside an if() takes ${letperf1[0]} ms for ${repeat} iterations (${letperf1[1]} per sec).`)
let varperf1 = getPerf(function(i) {
if (true) {
var a = i
}
}, repeat)
console.log(`'var' inside an if() takes ${varperf1[0]} ms for ${repeat} iterations (${varperf1[1]} per sec).`)
//-------outside a scope-----------
let letperf2 = getPerf(function(i) {
if (true) {}
let a = i
}, repeat)
console.log(`'let' outside an if() takes ${letperf2[0]} ms for ${repeat} iterations (${letperf2[1]} per sec).`)
let varperf2 = getPerf(function(i) {
if (true) {}
var a = i;
}, repeat);
console.log(`'var' outside an if() takes ${varperf2[0]} ms for ${repeat} iterations (${varperf2[1]} per sec).`)
@ardalanamini
Copy link
Author

This shows that 'let' is faster than 'var', but only when inside a different scope than the main scope of a function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment