Skip to content

Instantly share code, notes, and snippets.

@kei-s
Last active September 19, 2017 02:25
Show Gist options
  • Save kei-s/0c34cbe4e21a499601e8247077629082 to your computer and use it in GitHub Desktop.
Save kei-s/0c34cbe4e21a499601e8247077629082 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require 'benchmark'
class SizeMatters
include Comparable
attr :str
def <=>(other)
str.size <=> other.str.size
end
def initialize(str)
@str = str
end
def inspect
@str
end
end
Benchmark.bmbm do |x|
objA = SizeMatters.new("Z")
objB = SizeMatters.new("YY")
objV = SizeMatters.new("XXX")
x.report "[Integer] Comparable#between?" do
10000000.times { 10.between?(0, 100) }
end
x.report "[Integer] Comparable#clamp" do
10000000.times { 10.clamp(0, 100) }
end
x.report "[String] Comparable#between?" do
10000000.times { "b".between?("a", "z") }
end
x.report "[String] Comparable#clamp" do
10000000.times { "b".clamp("a", "z") }
end
x.report "[String] Comparable#<" do
10000000.times { "a" < "b" }
end
x.report "[Object] Comparable#between?" do
10000000.times { objV.between?(objA, objB) }
end
x.report "[Object] Comparable#clamp" do
10000000.times { objV.clamp(objA, objB) }
end
x.report "[Object] Comparable#<" do
10000000.times { objA < objB }
end
end
# ruby -v
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
# ruby /src/github.com/kei-s/sketch/ruby/comparable_bench.rb
user system total real
[Integer] Comparable#between? 1.430000 0.000000 1.430000 ( 1.433425)
[Integer] Comparable#clamp 1.820000 0.000000 1.820000 ( 1.818963)
[String] Comparable#between? 1.650000 0.000000 1.650000 ( 1.652295)
[String] Comparable#clamp 2.080000 0.000000 2.080000 ( 2.083517)
[String] Comparable#< 1.230000 0.000000 1.230000 ( 1.231948)
[Object] Comparable#between? 3.680000 0.000000 3.680000 ( 3.686492)
[Object] Comparable#clamp 4.930000 0.000000 4.930000 ( 4.936528)
[Object] Comparable#< 2.290000 0.000000 2.290000 ( 2.285007)
# /usr/local/bin/ruby -v
ruby 2.5.0dev (2017-09-13 trunk 59863) [x86_64-linux]
# ruby /src/github.com/kei-s/sketch/ruby/comparable_bench.rb
user system total real
[Integer] Comparable#between? 1.030000 0.000000 1.030000 ( 1.035063)
[Integer] Comparable#clamp 1.030000 0.000000 1.030000 ( 1.030999)
[String] Comparable#between? 1.210000 0.000000 1.210000 ( 1.216920)
[String] Comparable#clamp 1.460000 0.000000 1.460000 ( 1.458329)
[String] Comparable#< 1.080000 0.000000 1.080000 ( 1.075610)
[Object] Comparable#between? 3.920000 0.000000 3.920000 ( 3.916553)
[Object] Comparable#clamp 5.920000 0.000000 5.920000 ( 5.926508)
[Object] Comparable#< 2.730000 0.000000 2.730000 ( 2.738756)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment