Skip to content

Instantly share code, notes, and snippets.

@PragTob
Created October 23, 2015 15:47
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 PragTob/fdeb46356702bf9943ca to your computer and use it in GitHub Desktop.
Save PragTob/fdeb46356702bf9943ca to your computer and use it in GitHub Desktop.
instance_variable_get performance
require 'benchmark/ips'
class Test
def intitialize
@ivar = 'test'
end
def direct
@ivar
end
IVAR_NAME = "@ivar"
def hoist_ivar_name
instance_variable_get IVAR_NAME
end
def instance_variable_get_symbol
instance_variable_get :"@ivar"
end
def instance_variable_get_frozen
instance_variable_get('@ivar'.freeze)
end
def instance_variable_get_frozen_symbol
instance_variable_get('@ivar'.freeze.to_sym)
end
end
Benchmark.ips do |benchmark|
instance = Test.new
benchmark.report("direct") {instance.direct}
benchmark.report("hoist_ivar_name") {instance.hoist_ivar_name}
benchmark.report("ivar get symbol") {instance.instance_variable_get_symbol}
benchmark.report("ivar get frozen") {instance.instance_variable_get_frozen}
benchmark.report("ivar get frozen sym") {instance.instance_variable_get_frozen_symbol}
end
@justinjdickow
Copy link

ruby 2.6.0 (and newer hardware)

Warming up --------------------------------------
              direct     2.415M i/100ms
     hoist_ivar_name     1.101M i/100ms
     ivar get symbol     1.821M i/100ms
     ivar get frozen     1.136M i/100ms
 ivar get frozen sym     1.116M i/100ms
Calculating -------------------------------------
              direct     24.245M (± 0.9%) i/s -    123.177M in   5.080832s
     hoist_ivar_name     10.951M (± 0.6%) i/s -     55.056M in   5.027655s
     ivar get symbol     18.150M (± 1.0%) i/s -     91.067M in   5.017868s
     ivar get frozen     11.174M (± 3.1%) i/s -     56.781M in   5.086655s
 ivar get frozen sym     10.308M (± 5.6%) i/s -     52.456M in   5.106387s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment