Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda vs Proc in terms of memory and efficiency

Tags:

ruby

lambda

proc

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?

like image 941
MitulP91 Avatar asked Feb 15 '23 14:02

MitulP91


2 Answers

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]
    
like image 107
Abraham P Avatar answered Feb 18 '23 19:02

Abraham P


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.

like image 29
Jörg W Mittag Avatar answered Feb 18 '23 17:02

Jörg W Mittag