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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result:
Simple time benchmark (lower is better): user system total real Instance variable access: 0.024115 0.000012 0.024127 ( 0.024128) Getter access: 0.027965 0.000010 0.027975 ( 0.027979) Iterations per second (higher is better): ruby 3.4.1 (2024-12-25 revision 48d4efcb85) +PRISM [arm64-darwin23] Warming up -------------------------------------- Instance variable access: 3.571M i/100ms Getter access: 3.215M i/100ms Calculating ------------------------------------- Instance variable access: 35.951M (± 1.0%) i/s (27.82 ns/i) - 182.110M in 5.065990s Getter access: 31.687M (± 1.1%) i/s (31.56 ns/i) - 160.749M in 5.073622s Comparison: Instance variable access:: 35951125.5 i/s Getter access:: 31687428.0 i/s - 1.13x slower