Skip to content

Instantly share code, notes, and snippets.

@mudge
Created July 29, 2008 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mudge/3064 to your computer and use it in GitHub Desktop.
Save mudge/3064 to your computer and use it in GitHub Desktop.
Comparing two different implementations of a count method for arrays.
require 'benchmark'
class Array
def count_with_loop(elem)
enum = 0
each { |e| enum += 1 if elem == e }
enum
end
def count_without_loop(elem)
length - (self - [elem]).length
end
end
a = []
rand(10000).times { |i| a << rand(i) }
e = rand(10000)
Benchmark.bm(10) do |x|
x.report("count with loop") { 1000.times { a.count_with_loop(e) } }
x.report("count without loop") { 1000.times { a.count_without_loop(e) } }
end
# user system total real
# count with loop 5.030000 0.020000 5.050000 ( 5.077466)
# count without loop 0.390000 0.080000 0.470000 ( 0.466565)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment