Last active
June 5, 2017 15:03
-
-
Save rmosolgo/6c6a7d787e0f1666f4c6d858c8402a01 to your computer and use it in GitHub Desktop.
Calling a pure function in Ruby (benchmark)
This file contains 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" | |
# Let's say you want pure functions in Ruby. | |
# Which form of "packaging" is the fastest? | |
pure_func_proc = -> (a, b) { a + b } | |
pure_func_lambda = lambda { |a, b| a + b } | |
def pure_func_global(a, b) | |
a + b | |
end | |
method_obj_global = method(:pure_func_global) | |
module PureFunctionModule | |
def self.call_func(a, b) | |
a + b | |
end | |
PROC = -> (a, b) { a + b } | |
LAMBDA = lambda { |a, b| a + b } | |
end | |
class PureFunctionClass | |
def initialize(a, b) | |
@a = a | |
@b = b | |
end | |
def result | |
@a + @b | |
end | |
def self.call_func(a, b) | |
self.new(a, b).result | |
end | |
end | |
pure_function_instance = PureFunctionClass.new(3, 4) | |
Benchmark.ips do |x| | |
x.report("Local proc object") { pure_func_proc.call(3, 4) } | |
x.report("Local lambda object") { pure_func_lambda.call(3, 4) } | |
x.report("Global method") { pure_func_global(3, 4) } | |
x.report("Method object") { method_obj_global.call(3, 4) } | |
x.report("Module function") { PureFunctionModule.call_func(3, 4) } | |
x.report("Nested proc constant") { PureFunctionModule::PROC.call(3, 4) } | |
x.report("Nested lambda constant") { PureFunctionModule::LAMBDA.call(3, 4) } | |
x.report("Instance method") { pure_function_instance.result } | |
x.report("Initialize + instance method") { PureFunctionClass.new(3, 4).result } | |
x.report("Wrapper class method") { PureFunctionClass.call_func(3, 4) } | |
x.report("Inline call") { 3 + 4 } | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My result: short of writing the code inline, use a module function