Created
February 17, 2015 05:41
-
-
Save seako/639af70a2ca12cb5858a to your computer and use it in GitHub Desktop.
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' | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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