Question

I understand that there are different situations in which Procs and lambdas should be used (lambda checks number of arguments, etc.), but do they take up different amounts of memory? If so, which one is more efficient?

Was it helpful?

Solution

There are several differences between Lambdas and Procs.

  1. 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"
    
  2. 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]
    

OTHER TIPS

The Ruby Language Specification does not prescribe any particular implementation strategy for procs and lambdas, therefore any implementation is free to choose any strategy it wants, ergo any implementation may (or may not) take up completely different amounts of memory. Actually, this isn't just true for lambdas and procs, but for every kind of object. The Ruby Language Specification only prescribes the behavior of the objects, it does not prescribe any particular implementation or representation.

However, since there is only one class to represent both lambdas and procs, it is very likely that they take up the exact same amount of memory, regardless of how they are implemented and represented.

The differences between Proc and lambda are mostly behavior related, and are answered better by Abraham and is also found here

The old answer talked about how Block is faster than lambda as explained and shown at Ruby Monk:Ascent

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top