Last active
October 5, 2018 21:05
-
-
Save nknapp/0f16a7d54ace372e9a14258fd8d3c57a to your computer and use it in GitHub Desktop.
Should we really use anonymous functions as callback
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
function measure (description, fn) { | |
console.log('Running ' + description); | |
let start = Date.now(); | |
fn(100000000); | |
console.log(`Took ${Date.now() - start}ms\n`); | |
} | |
/** | |
* The scenario is: We want to call a lot of callbacks. | |
* Which is faster: The usual anonymous callback. | |
* Creating and instantiating a class with a callback method. | |
*/ | |
measure('anonymous callback', count => { | |
let sum = 0; | |
for (let i = 0; i < count; i++) { | |
sum = (x => x + i)(sum); | |
} | |
console.log(sum); | |
}); | |
measure('class', count => { | |
class Adder { | |
constructor(x) { | |
this.x = x; | |
} | |
add(y) { | |
return this.x + y; | |
} | |
} | |
let sum = 0; | |
for (let i = 0; i < count; i++) { | |
sum = new Adder(i).add(sum); | |
} | |
console.log(sum); | |
}); | |
measure('direct', count => { | |
let sum = 0; | |
for (let i = 0; i < count; i++) { | |
sum += i; | |
} | |
console.log(sum); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment