Skip to content

Instantly share code, notes, and snippets.

@albertywu
Last active October 13, 2015 18:56
Show Gist options
  • Select an option

  • Save albertywu/901aa9739b14479cd296 to your computer and use it in GitHub Desktop.

Select an option

Save albertywu/901aa9739b14479cd296 to your computer and use it in GitHub Desktop.
Boolean reduction via _.every, _.reduce, _.forEach, vanilla js
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
@albertywu

Copy link
Copy Markdown
Author

@bcherny the while(i--) performs the same as the vanilla for loop.

@bcherny

bcherny commented Oct 12, 2015

Copy link
Copy Markdown

tested unrolling the loops - seems like for is the best option - http://jsperf.com/reduce-vs-while-vs-for

@SimplGy

SimplGy commented Oct 13, 2015

Copy link
Copy Markdown

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