Created
April 23, 2025 14:26
-
-
Save lucianghinda/3264a3bea89aa40613b06815552d0771 to your computer and use it in GitHub Desktop.
Ruby - Benchmark Instance Variable vs Private Getters Access
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
require 'benchmark' | |
require 'benchmark/ips' | |
class TestClass | |
def initialize | |
@value = "test value" | |
end | |
def direct_access | |
@value | |
end | |
def reader_access | |
value | |
end | |
private | |
attr_reader :value | |
end | |
test_obj = TestClass.new | |
puts "Simple time benchmark (lower is better):" | |
Benchmark.bm(15) do |x| | |
x.report("Instance variable access:") { 1_000_000.times { test_obj.direct_access } } | |
x.report("Getter access:") { 1_000_000.times { test_obj.reader_access } } | |
end | |
puts "Iterations per second (higher is better):" | |
Benchmark.ips do |x| | |
x.report("Instance variable access:") { test_obj.direct_access } | |
x.report("Getter access:") { test_obj.reader_access } | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: