Skip to content

Instantly share code, notes, and snippets.

@kinduff
Last active June 20, 2024 17:42
Show Gist options
  • Save kinduff/24b8342cea250cbb6aa96b629674ce56 to your computer and use it in GitHub Desktop.
Save kinduff/24b8342cea250cbb6aa96b629674ce56 to your computer and use it in GitHub Desktop.
require 'benchmark'
class PersonClass
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
end
person = PersonClass.new("John", 30)
hash = { name: "John", age: 30 }
Benchmark.bmbm do |x|
x.report("Class attribute access") do
1_000_000.times do
person.name
person.age
end
end
x.report("Hash key access") do
1_000_000.times do
hash[:name]
hash[:age]
end
end
end
@kinduff
Copy link
Author

kinduff commented Jun 20, 2024

Ruby 3.2.2

With GC disabled:

Rehearsal ----------------------------------------------------------
Class attribute access   0.033338   0.000127   0.033465 (  0.033505)
Hash key access          0.036828   0.000000   0.036828 (  0.036859)
------------------------------------------------- total: 0.070293sec

                             user     system      total        real
Class attribute access   0.033789   0.000000   0.033789 (  0.033809)
Hash key access          0.036510   0.000000   0.036510 (  0.036533)

Without GC disabled:

Rehearsal ----------------------------------------------------------
Class attribute access   0.033027   0.000595   0.033622 (  0.033634)
Hash key access          0.037090   0.000000   0.037090 (  0.037102)
------------------------------------------------- total: 0.070712sec

                             user     system      total        real
Class attribute access   0.033549   0.000000   0.033549 (  0.033554)
Hash key access          0.036865   0.000000   0.036865 (  0.036885)

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