Skip to content

Instantly share code, notes, and snippets.

@jodosha
Last active June 27, 2022 08:31
Show Gist options
  • Save jodosha/03c941360bc49adf72470afae13004bc to your computer and use it in GitHub Desktop.
Save jodosha/03c941360bc49adf72470afae13004bc to your computer and use it in GitHub Desktop.
Ruby Benchmark: ivar vs accessor
#!/usr/bin/env ruby
# frozen_string_literal: true
require "benchmark/ips"
class Ivar
def initialize
@ivar = 23
end
def call
@ivar * 10
end
end
class AttrAccessor
def initialize
@ivar = 23
end
def call
ivar * 10
end
private
attr_reader :ivar
end
ivar = Ivar.new
attr = AttrAccessor.new
Benchmark.ips do |x|
x.report("ivar") { ivar.call }
x.report("attr") { attr.call }
x.compare!
end
__END__
Result:
Warming up --------------------------------------
ivar 1.646M i/100ms
attr 1.457M i/100ms
Calculating -------------------------------------
ivar 16.896M (± 2.9%) i/s - 85.613M in 5.071429s
attr 14.560M (± 2.5%) i/s - 72.854M in 5.006994s
Comparison:
ivar: 16895535.5 i/s
attr: 14559729.1 i/s - 1.16x (± 0.00) slower
Ruby:
ruby 3.1.0p0 (2021-12-25 revision fb4df44d16) [x86_64-darwin21]
Hardware:
Hardware Overview:
Model Name: MacBook Pro
Model Identifier: MacBookPro16,2
Processor Name: Quad-Core Intel Core i7
Processor Speed: 2,3 GHz
Number of Processors: 1
Total Number of Cores: 4
L2 Cache (per Core): 512 KB
L3 Cache: 8 MB
Hyper-Threading Technology: Enabled
Memory: 32 GB
System Firmware Version: 1731.120.10.0.0 (iBridge: 19.16.15071.0.0,0)
OS Loader Version: 540.120.3~6
Software:
System Software Overview:
System Version: macOS 12.4 (21F79)
Kernel Version: Darwin 21.5.0
Time since boot: 4 days 18:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment