Skip to content

Instantly share code, notes, and snippets.

@TALlama
Created December 22, 2010 23:21
Show Gist options
  • Save TALlama/752282 to your computer and use it in GitHub Desktop.
Save TALlama/752282 to your computer and use it in GitHub Desktop.
Spending way too much time optimizing code that does nothing, with metrics.
require 'benchmark'
def fizzbuzz_if(k)
k%3==0 ? (k%5==0 ? "fizzbuzz" : "fizz") : (k%5==0 ? "buzz" : k)
end
def fizzbuzz_d(k)
{true => {true => "fizzbuzz", false => "fizz"}, false => {true => "buzz"}}[k%3==0][k%5==0] || k
end
FIZZBUZZ_D_DICT = {true => {true => "fizzbuzz", false => "fizz"}, false => {true => "buzz"}}
def fizzbuzz_d_cached(k)
FIZZBUZZ_D_DICT[k%3==0][k%5==0] || k
end
def fizzbuzz_a(k)
[["fizzbuzz", %w{fizz} * 4].flatten, %w{buzz}, %w{buzz}][k%3][k%5] || k
end
FIZZBUZZ_A_ARRAY = [["fizzbuzz", %w{fizz} * 4].flatten, %w{buzz}, %w{buzz}]
def fizzbuzz_a_cached(k)
FIZZBUZZ_A_ARRAY[k%3][k%5] || k
end
100.times do |i|
answers = [fizzbuzz_if(i), fizzbuzz_d(i), fizzbuzz_d_cached(i), fizzbuzz_a(i), fizzbuzz_a_cached(i)]
raise Exception.new(answers.join(", ")) unless answers.uniq.length == 1
end
n = 5000000
Benchmark.bm(15) do |x|
x.report("if") { n.times do |i| fizzbuzz_if(i) end }
x.report("array") { n.times do |i| fizzbuzz_a(i) end }
x.report("array (cached)") { n.times do |i| fizzbuzz_a_cached(i) end }
x.report("dict") { n.times do |i| fizzbuzz_d(i) end }
x.report("dict (cached)") { n.times do |i| fizzbuzz_d_cached(i) end }
end
########### This is what my MBP gives: cached array is the winner by a nose
# user system total real
# if 1.150000 0.000000 1.150000 ( 1.152509)
# array 14.910000 0.040000 14.950000 ( 14.947081)
# array (cached) 0.910000 0.000000 0.910000 ( 0.917625)
# dict 15.530000 0.620000 16.150000 ( 16.144593)
# dict (cached) 1.420000 0.010000 1.430000 ( 1.420236)
@TALlama
Copy link
Author

TALlama commented Dec 22, 2010

Creating arrays and dictionaries is apparently pretty expensive; constructing those sieve objects and keeping them around make a huge difference.

Also interesting that a cached array is actually faster than the if logic itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment