Skip to content

Instantly share code, notes, and snippets.

@mindreframer
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindreframer/13984e072dfb864c2a81 to your computer and use it in GitHub Desktop.
Save mindreframer/13984e072dfb864c2a81 to your computer and use it in GitHub Desktop.
proc vs. direct method call
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