Last active
August 29, 2015 14:19
-
-
Save mindreframer/13984e072dfb864c2a81 to your computer and use it in GitHub Desktop.
proc vs. direct method call
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' | |
require 'json' | |
HASH = {'a'=>1, 'b'=>[1,2,3]} | |
class Roda | |
class << self | |
attr_accessor :opts | |
end | |
end | |
a = Proc.new { HASH.to_json } | |
class A | |
def self.a | |
HASH.to_json | |
end | |
end | |
Roda.opts = {} | |
Roda.opts[:json_result_serializer] = a | |
Roda.opts[:json_result_serializer_class] = A | |
n = 100000 | |
Benchmark.bm do |x| | |
x.report('proc') { for i in 1..n; Roda.opts[:json_result_serializer].call end } | |
x.report('class') { for i in 1..n; Roda.opts[:json_result_serializer_class].a end } | |
end | |
# user system total real | |
# proc 0.330000 0.000000 0.330000 ( 0.331962) | |
# class 0.310000 0.000000 0.310000 ( 0.311764) | |
# user system total real | |
# proc 0.350000 0.000000 0.350000 ( 0.358796) | |
# class 0.350000 0.000000 0.350000 ( 0.342676) | |
# 0.331962 / 0.311764 | |
# => 1.0647861844215496 | |
# 0.358796 / 0.342676 | |
# => 1.047041520269876 | |
## proc seems to be around 5% slower. It probably does not matter, you are right |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment