Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Last active August 29, 2015 14:14
Show Gist options
  • Save jgaskins/e9644d0ba7a9ff668c37 to your computer and use it in GitHub Desktop.
Save jgaskins/e9644d0ba7a9ff668c37 to your computer and use it in GitHub Desktop.
Object#extend vs proxy object performance
require 'benchmark/ips'
class Foo
def bar
# "Foo#bar"
end
end
module Bar
def bar
# "Bar#bar"
end
end
class FooWrapper
attr_reader :obj
def initialize(obj)
@obj = obj
end
def bar
# "FooWrapper#bar"
end
def method_missing *args, &block
obj.public_send *args, &block
end
end
Benchmark.ips do |x|
x.report "plain" do
Foo.new.bar
end
x.report "extend" do
Foo.new.extend(Bar).bar
end
x.report "proxy" do
FooWrapper.new(Foo.new).bar
end
end
# Calculating -------------------------------------
# plain 135.946k i/100ms
# extend 34.635k i/100ms
# proxy 112.357k i/100ms
# -------------------------------------------------
# plain 4.939M (± 5.0%) i/s - 24.742M
# extend 438.022k (± 4.1%) i/s - 2.217M
# proxy 2.676M (± 4.1%) i/s - 13.370M
@jgaskins
Copy link
Author

jgaskins commented Feb 3, 2015

Using Object#extend robs a whopping 90% of an object's performance by smashing the method cache. Using a proxy only slows it down by about 50%.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment