Skip to content

Instantly share code, notes, and snippets.

@dominikh
Created October 12, 2009 01:15
Show Gist options
  • Save dominikh/208027 to your computer and use it in GitHub Desktop.
Save dominikh/208027 to your computer and use it in GitHub Desktop.
require "benchmark"
def f(i); i; end
array = Array.new(1_000_000) { rand.to_s }
TESTS = 5
Benchmark.bmbm do |results|
results.report("null:") { TESTS.times { array.each { |i| f(i) } } }
results.report("sliced each:") { TESTS.times { array[1,array.size-2].each { |i| f(i) } } }
results.report("ranged each:") { TESTS.times { array[1...-1].each { |i| f(i) } } }
results.report("each on range:") { TESTS.times { (1...array.size).each { |i| f(array[i]) } } }
end
# Rehearsal --------------------------------------------------
# null: 1.790000 0.000000 1.790000 ( 1.827684)
# sliced each: 1.780000 0.000000 1.780000 ( 1.791690)
# ranged each: 1.780000 0.010000 1.790000 ( 1.796526)
# each on range: 2.360000 0.010000 2.370000 ( 2.369797)
# ----------------------------------------- total: 7.730000sec
#
# user system total real
# null: 1.810000 0.000000 1.810000 ( 1.817914)
# sliced each: 1.800000 0.010000 1.810000 ( 1.813449)
# ranged each: 1.800000 0.000000 1.800000 ( 1.798177)
# each on range: 2.340000 0.000000 2.340000 ( 2.363105)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment