Skip to content

Instantly share code, notes, and snippets.

@davidjbeveridge
Created October 26, 2012 21:47
Show Gist options
  • Save davidjbeveridge/3961762 to your computer and use it in GitHub Desktop.
Save davidjbeveridge/3961762 to your computer and use it in GitHub Desktop.
javascript function memoization benchmark
fib1 = (index) ->
if index < 2
1
else
fib1(index - 1) + fib1(index - 2)
fib2 = (index) ->
hash = {}
fib2 = (index) ->
hash[index] or= if index < 2
1
else
fib2(index - 1) + fib2(index - 2)
fib2(index)
runtime = (start, end) ->
(end.getTime() - start.getTime()) / 1000
benchmark = (max) ->
start1 = new Date
fib1(i) for i in [0..max]
end1 = new Date
start2 = new Date
fib2(i) for i in [0..max]
end2 = new Date
run1 = runtime(start1, end1)
run2 = runtime(start2, end2)
console.log "Recursion: #{run1}s"
console.log "Memoized Recursion: #{run2}s"
benchmark 40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment