hello, quick question - if I have a procedure that calculates the same thing twice (e.g., the cdr of a list), would it run faster if I bound that with a let?
as in, is the compiler able to spot that I’m calling the same function multiple times with the same argument in the body of my function, and optimise it to actually call it once and re-use the result? or would I need to do that manually with a let?
so if the call to (f a b)
appear twice in the body of my function, will the compiler only call it once? or do I need to do (let ((x (f a b)) ...)
to do that?
The Racket compiler (either traditional or on Chez Scheme) does not currently perform common-subexpression elimination, so you would have to use a let
to make sure a call happens only once. For something like cdr
, you probably won’t be able to tell the difference — but it can matter for more complex expressions, of course.
thanks @mflatt - am I right in thinking that first and rest are just about following a pointer, and therefore as you say it doesn’t make sense to bind them in a let?
@cmscalzo first and rest are quick operations as you suspect, and thus I wouldn’t worry about them unless you have reason to based on measurements
great, thanks @samth