Skip to content

Instantly share code, notes, and snippets.

@schneems
Last active January 28, 2022 14:22
Show Gist options
  • Save schneems/08faee64c033c51e7f79e94381bfbc07 to your computer and use it in GitHub Desktop.
Save schneems/08faee64c033c51e7f79e94381bfbc07 to your computer and use it in GitHub Desktop.

Revisions

  1. schneems revised this gist Jan 26, 2022. 1 changed file with 2 additions and 13 deletions.
    15 changes: 2 additions & 13 deletions return_object_bench.rb
    Original file line number Diff line number Diff line change
    @@ -17,18 +17,7 @@ def add(a,b)
    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.report("obj return") { foo = Add.new(1, 2); foo.result; foo.is_negative }
    x.report("hash 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
  2. schneems created this gist Jan 26, 2022.
    34 changes: 34 additions & 0 deletions return_object_bench.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    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