Last active
October 13, 2015 18:56
-
-
Save albertywu/901aa9739b14479cd296 to your computer and use it in GitHub Desktop.
Boolean reduction via _.every, _.reduce, _.forEach, vanilla js
This file contains hidden or 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
| trues = (n) -> [1..n].map Boolean | |
| # array of functions to be speed tested | |
| tests = [ | |
| [ | |
| ( | |
| (bools) -> _.every bools # .097ms | |
| ) | |
| trues(1000) | |
| '1' | |
| ] | |
| [ | |
| ( | |
| (bools) -> | |
| bools.reduce (p, n) -> # .161ms | |
| return false unless n | |
| p or n | |
| , false | |
| ) | |
| trues(1000) | |
| '2' | |
| ] | |
| [ | |
| ( | |
| (bools) -> | |
| bools.forEach (b) -> return false unless b # .141ms | |
| return true | |
| ) | |
| trues(1000) | |
| '3' | |
| ] | |
| [ | |
| ( | |
| (bools) -> | |
| for b in bools | |
| return false unless b # FAST: .014ms | |
| return true | |
| ) | |
| trues(1000) | |
| '4' | |
| ] | |
| ] | |
| speedTestFn = (fn, arg, label) -> | |
| console.time label | |
| fn(arg) | |
| console.timeEnd label | |
| results = [] | |
| tests.forEach ([fn, arg, label]) -> | |
| results = speedTestFn fn, arg, label |
Wow. Way to go on testing this. Any theories on the "why"? I think it's the function scope creation...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
tested unrolling the loops - seems like
foris the best option - http://jsperf.com/reduce-vs-while-vs-for