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?
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With