Created
July 29, 2008 11:10
-
-
Save mudge/3064 to your computer and use it in GitHub Desktop.
Comparing two different implementations of a count method for arrays.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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