cmscalzo
2019-10-28 12:16:46

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?


cmscalzo
2019-10-28 12:17:41

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?


cmscalzo
2019-10-28 12:19:06

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?


mflatt
2019-10-28 12:45:15

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.


cmscalzo
2019-10-28 13:00:42

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?


samth
2019-10-28 13:10:35

@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


cmscalzo
2019-10-28 13:21:55

great, thanks @samth