marleynoe
marleynoe

Reputation: 121

let vs let* in LISP - is there a difference in efficiency?

This should be a quick one: I've been asking myself often whether there's a difference in efficiency between the LISP special functions let and let*? For instance, are they equivalent when creating only one variable?

Upvotes: 2

Views: 241

Answers (2)

Daniel Jour
Daniel Jour

Reputation: 16156

As Barmar pointed out, there shouldn't be any performance difference in "production ready" Lisps.

For CLISP, both of these produce the same (bytecode) assembly:

(defun foo (x) (let ((a x) (b (* x 2))) (+ a b)))
(defun bar (x) (let* ((a x) (b (* x 2))) (+ a b)))

Though for non-optimizing, simple interpreters (or also compilers) there could very well be a difference, e.g. because let* and let could be implemented as simple macros, and a single lambda with multiple parameters is probably more efficient than multiple lambdas with a single parameter each:

;; Possible macro expansion for foo's body
(funcall #'(lambda (a b) (+ a b)) x (* x 2))
;; Possible macro expansion for bar's body
(funcall #'(lambda (a) (funcall #'(lambda (b) (+ a b)) (* x 2))) x)

Having multiple lambdas, as well as the (avoidable) closing over a could make the second expansion less "efficient".

When used with only one binding, then there shouldn't be any difference even then, though.

But if you're using an implementation that isn't optimizing let* (or let), then there's probably no point discussing performance at all.

Upvotes: 4

Barmar
Barmar

Reputation: 780724

There shouldn't be any performance difference. The only difference between them is the scope of the variables, which is dealt with at compile time. If there's only one variable, there's absolutely no difference.

Upvotes: 3

Related Questions