Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would Common Lisp (SBCL) use so much memory for a simple program?

since I'm a newbie to Common Lisp I tried to solve problems on SPOJ by using Common Lisp (SBCL). The first problem is a simple task of reading numbers until number 42 is found. Here's my solution:

(defun study-num ()
  (let ((num (parse-integer (read-line t))))
    (when (not (= num 42))
      (format t "~A~%" num)
      (study-num))))
(study-num)

The solution is accepted. But when I looked into the details of the result I found it used 57M of MEM! It's bloody unreasonable but I can't figure out why. What can I do to make an optimization?

like image 377
lastland Avatar asked Dec 13 '22 05:12

lastland


1 Answers

You are making repeated recursive calls, without enough optimization switched on to enable tail-call elimination (SBCL does do this, but only when you have "optimize for speed" set high and "optimize for debug info" set low).

The Common Lisp standard leaves tail-call elimination as an implementation quality issue and provides other looping constructs (like LOOP or DO, both possibly suitable for this application).

In addition, a freshly started SBCL is probably going to be larger than you expect, due to needing to pull in its runtime environment and base image.

like image 184
Vatine Avatar answered Apr 09 '23 07:04

Vatine