Skip to content

Instantly share code, notes, and snippets.

@asterite
Created October 5, 2020 17:53
Show Gist options
  • Select an option

  • Save asterite/b9f4fedfeff6c46137dd1e8e34902f7b to your computer and use it in GitHub Desktop.

Select an option

Save asterite/b9f4fedfeff6c46137dd1e8e34902f7b to your computer and use it in GitHub Desktop.

Revisions

  1. asterite created this gist Oct 5, 2020.
    41 changes: 41 additions & 0 deletions constants_vs_inline.cr
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    require "benchmark"

    RANGE = 3..7

    a = 1
    v = ARGV[0].to_i

    Benchmark.ips do |x|
    x.report("constant") do
    case v
    when RANGE
    a &+= 1
    end
    end
    x.report("inline") do
    case v
    when 3..7
    a &+= 1
    end
    end
    x.report("manual") do
    if 3 <= v <= 7
    a &+= 1
    end
    end
    end

    puts a


    # Results

    ## Current compiler
    # constant 291.75M ( 3.43ns) (± 8.16%) 0.0B/op 2.66× slower
    # inline 769.21M ( 1.30ns) (± 6.62%) 0.0B/op 1.01× slower
    # manual 777.14M ( 1.29ns) (± 7.07%) 0.0B/op fastest

    ## Next compiler
    # constant 605.09M ( 1.65ns) (± 4.55%) 0.0B/op 1.15× slower
    # inline 697.44M ( 1.43ns) (± 5.34%) 0.0B/op fastest
    # manual 601.71M ( 1.66ns) (± 5.20%) 0.0B/op 1.16× slower