Skip to content

Instantly share code, notes, and snippets.

@jrunning
Last active September 12, 2016 22:04
Show Gist options
  • Save jrunning/fe7c06ce17079d917a5d8dc7b65406c7 to your computer and use it in GitHub Desktop.
Save jrunning/fe7c06ce17079d917a5d8dc7b65406c7 to your computer and use it in GitHub Desktop.
require "benchmark/ips"
NUMBERS = (0..100).to_a.shuffle
STRINGS = ("abcd".."efgh").to_a.shuffle
def val
case rand(0..1)
when 0 then NUMBERS.sample
else STRINGS.sample
end
end
def clever(arr)
arr.reject &String.method(:===)
end
def unclever(arr)
arr.reject {|s| String === s }
end
vals = Array.new(10000) { val }
Benchmark.ips do |x|
x.report("clever") { clever(vals) }
x.report("unclever") { unclever(vals) }
x.compare!
end
$ ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
$ ruby 01_clever_vs_unclever.rb
Warming up --------------------------------------
clever 109.000 i/100ms
unclever 126.000 i/100ms
Calculating -------------------------------------
clever 1.110k (± 2.4%) i/s - 5.559k in 5.012965s
unclever 1.297k (± 3.6%) i/s - 6.552k in 5.058913s
Comparison:
unclever: 1297.0 i/s
clever: 1109.6 i/s - 1.17x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment