Created
April 15, 2015 16:16
-
-
Save edelpero/90c751a59ca8f13eae94 to your computer and use it in GitHub Desktop.
Compares method execution performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark/ips' | |
class A | |
def sum | |
1 + 1 | |
end | |
end | |
class B | |
def sum | |
eval("1 + 1") | |
end | |
end | |
class C | |
define_method(:sum) { | |
1 + 1 | |
} | |
end | |
class D | |
def sum | |
Proc.new { 1 + 1 }.call | |
end | |
end | |
class E | |
def sum | |
-> { 1 + 1 }.call | |
end | |
end | |
Benchmark.ips do |x| | |
x.config(:time => 20, :warmup => 2) | |
x.report("Using method") do | |
A.new.sum | |
end | |
x.report("Using eval") do | |
B.new.sum | |
end | |
x.report("Using define_method") do | |
C.new.sum | |
end | |
x.report("Using proc") do | |
D.new.sum | |
end | |
x.report("Using lambda") do | |
E.new.sum | |
end | |
x.compare! | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Calculating ------------------------------------- | |
Using method 86.320k i/100ms | |
Using eval 12.111k i/100ms | |
Using define_method 86.212k i/100ms | |
Using proc 48.346k i/100ms | |
Using lambda 49.955k i/100ms | |
------------------------------------------------- | |
Using method 3.404M (± 6.2%) i/s - 67.761M | |
Using eval 137.423k (± 9.7%) i/s - 2.725M | |
Using define_method 2.807M (± 5.9%) i/s - 55.952M | |
Using proc 791.085k (± 7.9%) i/s - 15.712M | |
Using lambda 852.819k (± 6.3%) i/s - 16.985M | |
Comparison: | |
Using method: 3403761.0 i/s | |
Using define_method: 2807353.2 i/s - 1.21x slower | |
Using lambda: 852819.4 i/s - 3.99x slower | |
Using proc: 791085.4 i/s - 4.30x slower | |
Using eval: 137423.1 i/s - 24.77x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment