Skip to content

Instantly share code, notes, and snippets.

@seako
Created February 17, 2015 05:41
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 seako/639af70a2ca12cb5858a to your computer and use it in GitHub Desktop.
Save seako/639af70a2ca12cb5858a to your computer and use it in GitHub Desktop.
require 'benchmark'
class LocalLambda
def local_lambda
a_lambda = -> { 1 }
a_lambda.call
1
end
def nested_definition
def a_nested_def
1
end
a_nested_def
1
end
end
test = LocalLambda.new
Benchmark.bm(10) do |x|
x.report("local_lambda:") { (0...1_000_000).each { test.local_lambda } }
x.report("nested_definition:") { (0...1_000_000).each { test.nested_definition} }
end
@seako
Copy link
Author

seako commented Feb 17, 2015

As I learned from http://stackoverflow.com/questions/4864191/is-it-possible-to-have-methods-inside-methods/4865161#4865161, Ruby doesn't have nested method definitions. You can define a method inside of a method definition but this will not define a method only visible within the enclosing method definition's scope, it will define an instance method each time the enclosing method is called. To achieve an effect like a nested method definition you can create a lambda inside the enclosing method. This lambda will be created every time the enclosing method is called but it won't be callable outside the scope of the method definition.

I wrote this benchmark to compare the overhead of creating the lambda to redefining the method. Here's the results of the last run I did on ruby 2.2.0

                 user     system      total        real
local_lambda:  0.500000   0.010000   0.510000 (  0.498791)
nested_definition:  1.030000   0.000000   1.030000 (  1.042816)

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