Created
July 19, 2017 10:07
dig benchmark for fluentd
This file contains 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 Test0 | |
def initialize(key) | |
@key = key | |
end | |
def call(record) | |
record[@key] | |
end | |
end | |
class Test1 | |
def initialize(keys) | |
@keys = keys | |
end | |
def call(record) | |
record.dig(*@keys) | |
end | |
end | |
class Test2 | |
def initialize(keys) | |
__str_eval_code__ = create_handler(keys) | |
(class << self; self; end).class_eval <<-EORUBY, __FILE__, __LINE__ + 1 | |
def call(r) | |
#{__str_eval_code__} | |
end | |
EORUBY | |
end | |
def call(r) | |
end | |
end | |
def create_handler(keys) | |
args = [] | |
keys.each { |key| | |
case key | |
when String | |
args << "'#{key}'.freeze" | |
when Integer | |
args << key.to_s | |
else | |
raise "Unsupported key type: #{key}" | |
end | |
} | |
"r.dig(#{args.join(',')})" | |
end | |
h = {'foo' => {'bar' => [0, 1, 2]}} | |
keys = ['foo', 'bar', 1] | |
n = 5000000 | |
t0 = Test0.new('foo') # baseline | |
t1 = Test1.new(keys) | |
t2 = Test2.new(keys) | |
os1 = os2 = os3 = os4 = nil | |
GC.disable | |
Benchmark.bm do |x| | |
x.report { | |
n.times do | |
t0.call(h) | |
end | |
} | |
x.report { | |
#os1 = ObjectSpace.count_objects | |
n.times do | |
t1.call(h) | |
end | |
#os2 = ObjectSpace.count_objects | |
} | |
x.report { | |
#os3 = ObjectSpace.count_objects | |
n.times do | |
t2.call(h) | |
end | |
#os4 = ObjectSpace.count_objects | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment