Sha256: 341eff439a9c3428f90f5a0f0e076d41bb484a5d5a3df9659fd042dbdd8ba4af

Contents?: true

Size: 981 Bytes

Versions: 39

Compression:

Stored size: 981 Bytes

Contents

require "benchmark"

module Wrapper
  def self.extended(klass)
    klass.class_eval do
      @@methods = {}
      def self.methods
        @@methods
      end
      def self.set_method k, v
        @@methods[k] = v
      end
    end
  end

  def method_added name
    return if methods.include?(name)
    puts "#{name} added"
    set_method(name, instance_method(name))
    class_eval %{
      def #{name}(*args)
        self.class.methods[#{name.inspect}].bind(self).call(*args)
      end
    }, __FILE__, __LINE__ + 1
  end
end

class NotWrapped
  def add a, b
    a + b
  end
end

class Wrapped
  extend ::Wrapper
  def add a, b
    a + b
  end
end

w = Wrapped.new
nw = NotWrapped.new
# p w.add(1, 4)
# exit
# 30 is the width of the output column
Benchmark.bm 30 do |x|
  x.report "wrapped" do
    100_000.times do |_|
      w.add(rand(1000), rand(1000))
    end
  end
  x.report "not wrapped" do
    100_000.times do |_|
      nw.add(rand(1000), rand(1000))
    end
  end
end

Version data entries

39 entries across 30 versions & 7 rubygems

Version Path
contracts-0.17.2 benchmarks/wrap_test.rb
contracts-0.17.1 benchmarks/wrap_test.rb
entitlements-app-1.1.0 lib/contracts-ruby3/benchmarks/wrap_test.rb
entitlements-app-1.1.0 lib/contracts-ruby2/benchmarks/wrap_test.rb
entitlements-app-1.0.0 lib/contracts-ruby2/benchmarks/wrap_test.rb
entitlements-app-1.0.0 lib/contracts-ruby3/benchmarks/wrap_test.rb
entitlements-app-0.3.4 lib/contracts-ruby3/benchmarks/wrap_test.rb
entitlements-app-0.3.4 lib/contracts-ruby2/benchmarks/wrap_test.rb
entitlements-app-0.3.1 lib/contracts-ruby3/benchmarks/wrap_test.rb
entitlements-app-0.3.1 lib/contracts-ruby2/benchmarks/wrap_test.rb
honeybadger-5.4.0 vendor/bundle/ruby/3.2.0/gems/contracts-0.17/benchmarks/wrap_test.rb
honeybadger-5.3.0 vendor/bundle/ruby/3.2.0/gems/contracts-0.17/benchmarks/wrap_test.rb
entitlements-app-0.3.0 lib/contracts-ruby3/benchmarks/wrap_test.rb
entitlements-app-0.3.0 lib/contracts-ruby2/benchmarks/wrap_test.rb
entitlements-0.2.1 lib/contracts-ruby3/benchmarks/wrap_test.rb
entitlements-0.2.1 lib/contracts-ruby2/benchmarks/wrap_test.rb
entitlements-app-0.2.1 lib/contracts-ruby2/benchmarks/wrap_test.rb
entitlements-app-0.2.1 lib/contracts-ruby3/benchmarks/wrap_test.rb
entitlements-0.2.0 lib/contracts-ruby2/benchmarks/wrap_test.rb
entitlements-0.2.0 lib/contracts-ruby3/benchmarks/wrap_test.rb