Last active
January 28, 2022 14:22
-
-
Save schneems/08faee64c033c51e7f79e94381bfbc07 to your computer and use it in GitHub Desktop.
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
| class Add | |
| attr_reader :result, :is_negative | |
| def initialize(a, b) | |
| @result = a + b | |
| @is_negative = @result < 0 | |
| end | |
| end | |
| def add(a,b) | |
| result = a + b | |
| { result: result, is_negative: (result < 0) } | |
| end | |
| require 'benchmark/ips' | |
| Benchmark.ips do |x| | |
| x.report("hash return") { foo = Add.new(1, 2); foo.result; foo.is_negative } | |
| x.report("obj return ") { foo = add(1, 2); foo[:result]; foo[:is_negative] } | |
| x.compare! | |
| end | |
| # Warming up -------------------------------------- | |
| # hash return 534.436k i/100ms | |
| # obj return 695.817k i/100ms | |
| # Calculating ------------------------------------- | |
| # hash return 5.490M (± 2.8%) i/s - 27.791M in 5.065681s | |
| # obj return 7.062M (± 4.1%) i/s - 35.487M in 5.034689s | |
| # Comparison: | |
| # obj return : 7062192.3 i/s | |
| # hash return: 5490408.9 i/s - 1.29x (± 0.00) slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment