What's the difference between a proc and a lambda in Ruby?
One difference is in the way they handle arguments. Creating a proc using proc {}
and Proc.new {}
are equivalent. However, using lambda {}
gives you a proc that checks the number of arguments passed to it. From ri Kernel#lambda
:
Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.
An example:
p = Proc.new {|a, b| puts a**2+b**2 } # => #<Proc:0x3c7d28@(irb):1>
p.call 1, 2 # => 5
p.call 1 # => NoMethodError: undefined method `**' for nil:NilClass
p.call 1, 2, 3 # => 5
l = lambda {|a, b| puts a**2+b**2 } # => #<Proc:0x15016c@(irb):5 (lambda)>
l.call 1, 2 # => 5
l.call 1 # => ArgumentError: wrong number of arguments (1 for 2)
l.call 1, 2, 3 # => ArgumentError: wrong number of arguments (3 for 2)
In addition, as Ken points out, using return
inside a lambda returns the value of that lambda, but using return
in a proc returns from the enclosing block.
lambda { return :foo }.call # => :foo
return # => LocalJumpError: unexpected return
Proc.new { return :foo }.call # => LocalJumpError: unexpected return
So for most quick uses they're the same, but if you want automatic strict argument checking (which can also sometimes help with debugging), or if you need to use the return
statement to return the value of the proc, use lambda
.
Speed differences between proc, Proc.new, lambda, and stabby lambda
So it seems you have three questions. The middle one is unclear to me, so I will address the other two:
Why is normal method invocation so much faster?
This is the easier of the questions.
First realize that the times involved here are for function call overhead. I did my own timings based on your code (but with an identity function instead of multiplication), and non-direct invocations took 49% longer. With one multiplication, non-direct invocations took only 43% longer. In other words, one reason why you're seeing a large disparity is that your function itself is doing almost nothing. Even a single multiplication makes 6% of the difference "vanish". In a method of any reasonable complexity, the method call overhead is usually going to be a relatively small percentage of the overall time.
Next, remember that a proc/block/lambda is essentially a chunk of code that is being carried around (though a block literal cannot be saved into a variable). This implies one more level of indirection than a method call...meaning that at the very least the CPU is going to have to traverse a pointer to something.
Also, remember that Ruby supports closures, and I'm betting there is some overhead in deciding which environment the indirect code should run in.
On my machine, running a C program that invokes a function directly has 10% less overhead than one that uses a pointer to a function. An interpreted language like Ruby, where closures are also involved, is definitely going to use more.
My measurements (Ruby 2.2) indicate a direct method invocation takes about as long as 6 multiplications, and an indirect invocation takes about as long as 10.
So while the overhead is nearly twice as large, remember that the overhead in both cases is often relatively small.
Are there any other (performance based) reasons to chose between the different approaches?
I'd say given the above data the answer is usually no: you're much better off using the construct that gives you the most maintainable code.
There are definitely good reasons to choose one over the other. To be honest, I'm surprised about the difference I see between lambdas and blocks (on my machine, lambdas have 20% less overhead). Lambdas create anonymous methods that include parameter list checking, so if anything I would expect it to be slightly slower, but my measurements put it ahead.
That the direct invocation is faster simply isn't surprising at all.
The place where this kind of thing makes a difference is in very frequently called code where the overhead adds up to be noticeable in wall-clock kinds of ways. In this case, it can make sense to do all manner of ugly optimizations to try to squeeze a bit more speed, all the way up to inlining code (dodge the function-call overhead altogether).
For example, say your application uses a database framework. You profile it and find a frequently-called, small (e.g. less than 20 multiplications worth of work) function that copies the data from the database result into data structures. Such a function might comprise the lion's share of the result processing, and simply inlining that function might shave off significant amounts of CPU time at the expense of some code clarity.
Simply inlining your "square function" into a long numeric calculation with a billion steps could save you dramatic amounts of time because the operation itself takes a lot less time than even a direct method invocation.
In most cases, though, you're better off with clean, clear code.
When to use lambda, when to use Proc.new?
Another important but subtle difference between procs created with lambda
and procs created with Proc.new
is how they handle the return
statement:
- In a
lambda
-created proc, thereturn
statement returns only from the proc itself - In a
Proc.new
-created proc, thereturn
statement is a little more surprising: it returns control not just from the proc, but also from the method enclosing the proc!
Here's lambda
-created proc's return
in action. It behaves in a way that you probably expect:
def whowouldwin
mylambda = lambda {return "Freddy"}
mylambda.call
# mylambda gets called and returns "Freddy", and execution
# continues on the next line
return "Jason"
end
whowouldwin
#=> "Jason"
Now here's a Proc.new
-created proc's return
doing the same thing. You're about to see one of those cases where Ruby breaks the much-vaunted Principle of Least Surprise:
def whowouldwin2
myproc = Proc.new {return "Freddy"}
myproc.call
# myproc gets called and returns "Freddy",
# but also returns control from whowhouldwin2!
# The line below *never* gets executed.
return "Jason"
end
whowouldwin2
#=> "Freddy"
Thanks to this surprising behavior (as well as less typing), I tend to favor using lambda
over Proc.new
when making procs.
Differences between Proc and Lambda
There are two main differences between lambdas and non-lambda Proc
s:
- Just like methods, lambdas return from themselves, whereas non-lambda
Proc
s return from the enclosing method, just like blocks. - Just like methods, lambdas have strict argument checking, whereas non-lambda
Proc
s have loose argument checking, just like blocks.
Or, in short: lambdas behave like methods, non-lambda Proc
s behave like blocks.
What you are seeing there is an instance of #2. Try it with a block and a method in addition to a non-lambda Proc
and a lambda, and you'll see. (Without this behavior, Hash#each
would be a real PITA to use, since it does yield an array with two-elements, but you pretty much always want to treat it as two arguments.)
Ruby Lambda vs. Proc LocalJumpError
Here's an answer I gave to a related question. It talks a bit about lambda vs proc and LocalJumpErrors.
In a proc, return
is a special piece of syntax that returns from the lexical scope of the proc, not the proc itself. So it's trying to return out of procBuilder
, which has already exited.
There are a couple ways to fix this:
- Don't use
return
at all. Ruby will return control to proc's caller all on its own. - Change
proc
tolambda
, which behaves the way you expect. Lambdas act like methods; procs act like blocks.
As for the error you're expecting, you shouldn't get that. procBuilder
returns a proc that encloses the message variable. You don't need any arguments to the proc itself.
Edit: answering your additional question. The proc is a closure. It has "captured" the message variable (a local variable in procBuilder
), which was in scope when the proc was created. The proc now can wander through your program with the message variable hidden inside of it, ready to be printed when you call it. The only trouble is the return statement, which has the additional requirement that it the lexical scope still be "live".
The reason for all this is that this behavior is really helpful in blocks. In this case, it's not helpful at all, so you should just use a lambda
, where return means something less insane.
A really great tutorial on closures in ruby: http://innig.net/software/ruby/closures-in-ruby.rb
Lambda vs Proc in terms of memory and efficiency
There are several differences between Lambdas and Procs.
Lambdas have what are known as "diminutive returns". What that means is that a Lambda will return flow to the function that called it, while a Proc will return out of the function that called it.
def proc_demo
Proc.new { return "return value from Proc" }.call
"return value from method"
end
def lambda_demo
lambda { return "return value from lambda" }.call
"return value from method"
end
proc_demo #=> "return value from Proc"
lambda_demo #=> "return value from method"Lambdas check the number of parameters passed into them, while Procs do not. For example:
lambda { |a, b| [a, b] }.call(:foo)
#=> #<ArgumentError: wrong number of arguments (1 for 2)>
Proc.new { |a, b| [a, b] }.call(:foo)
#=> [:foo, nil]
proc return vs lambda return
You should see comment in this answer https://stackoverflow.com/a/723/4576274.
It states
A lambda is an anonymous method. Since it's a method, it returns a
value, and the method that called it can do with it whatever it wants,
including ignoring it and returning a different value.A Proc is like
pasting in a code snippet. It doesn't act like a method. So when a
return happens within the Proc, that's just part of the code of the
method that called it
Related Topics
How to Get a List of Files That Have Been 'Required' in Ruby
Ruby Create Recursive Directory Tree
Share Models Between 2 Rails API's (Separate Applications)
How to Update Gems in Ruby for Windows
Multiple Blogs in Single Jekyll Website
What's the Fastest Way to Check If a Word from One String Is in Another String
Why Relative Path Doesn't Work in Ruby Require
Phusion Passenger Is Throwing Errors After Upgrading Ruby and Rails Using Rvm
Rendering Haml Partials from Within Haml Outside of Rails
Retrieve Contents of Url as String
How to Load Some Activerecord Models from a Yaml File and Save Them to the Db
Split Array into Sub-Arrays Based on Value
Can't Convert Symbol into String
Ruby: "&& Return" VS "And Return"
Rails 4 - Syntax Error, Unexpected Tidentifier, Expecting End-Of-Input