Last active
June 24, 2022 16:57
-
-
Save texpert/07143266d762885f4a7bde390863bb17 to your computer and use it in GitHub Desktop.
Ruby constant lookup vs const_get benchmark
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
Warming up -------------------------------------- | |
lookup 1.241M i/100ms | |
const_get 1.111M i/100ms | |
Calculating ------------------------------------- | |
lookup 13.510M (± 0.7%) i/s - 135.305M in 10.031861s | |
const_get 11.373M (± 0.5%) i/s - 114.446M in 10.072033s | |
with 95.0% confidence | |
Comparison: | |
lookup: 13509513.8 i/s | |
const_get: 11372746.2 i/s - 1.19x (± 0.01) slower | |
with 95.0% confidence | |
Source Code: | |
----------------------------- | |
# frozen_string_literal: true | |
require 'benchmark/ips' | |
# Enable and start GC before each job run. Disable GC afterwards. | |
# | |
# Inspired by https://www.omniref.com/ruby/2.2.1/symbols/Benchmark/bm?#annotation=4095926&line=182 | |
class GCSuite | |
def warming(*) | |
run_gc | |
end | |
def running(*) | |
run_gc | |
end | |
def warmup_stats(*) | |
end | |
def add_report(*) | |
end | |
private | |
def run_gc | |
GC.enable | |
GC.start | |
GC.disable | |
end | |
end | |
GCSuite.new | |
class Lookup | |
def foo | |
self.class::Foo | |
end | |
end | |
class LookupBar < Lookup | |
class Foo | |
end | |
end | |
class ConstGet | |
def foo | |
self.class.const_get(:Foo) | |
end | |
end | |
class ConstGetBar < ConstGet | |
class Foo | |
end | |
end | |
l = LookupBar.new | |
c = ConstGetBar.new | |
Benchmark.ips do |x| | |
x.config(:time => 10, :warmup => 5, :stats => :bootstrap, :confidence => 95) | |
x.report('lookup') do | |
l.foo | |
end | |
x.report('const_get') do | |
c.foo | |
end | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment