Skip to content

Instantly share code, notes, and snippets.

@Papierkorb
Created July 6, 2016 19:07
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 Papierkorb/c56c874ea4feac772b12fb62aa6eb080 to your computer and use it in GitHub Desktop.
Save Papierkorb/c56c874ea4feac772b12fb62aa6eb080 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#frozen-string-literal: true
require 'benchmark'
chain = [ 'to_i', 'zero?' ]
CALLS = 1_000_000
var = 123
Benchmark.bm(10) do |x|
x.report 'inject' do
CALLS.times do
chain.inject(var){|val, meth| val.public_send(meth)}
end
end
x.report 'eval' do
f = eval("->(val){ val.#{chain.join '.'} }")
CALLS.times{ f.call(var) }
end
end
user system total real
inject 0.460000 0.000000 0.460000 ( 0.464011)
eval 0.090000 0.000000 0.090000 ( 0.091068) #=> ~5.1x faster
CPU: i5-6600K (4x3.5 GHz)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment