Created
February 24, 2018 20:22
-
-
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
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
/** | |
* 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).`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This shows that 'let' is faster than 'var', but only when inside a different scope than the main scope of a function