问题描述
由于我是Common Lisp的新手,因此我尝试使用Common Lisp解决上的问题( )。 是读取数字直到找到数字42的简单任务。这是我的解决方案:
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)
该解决方案被接受。但是,当我查看结果的详细信息时,发现它使用了57M的MEM!血腥的不合理,但我不知道为什么。我该怎么做才能进行优化?
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?
推荐答案
您正在重复进行递归调用,而没有启用足够的优化以启用tail-消除呼叫(SBCL会执行此操作,但仅当您将针对速度优化设置为高,而将针对调试信息优化设置为低时)。
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).
Common Lisp标准将消除尾音作为实现质量问题,并提供了其他循环构造(例如LOOP或DO,两者都可能适用于此应用程序)。
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).
此外,由于需要引入运行时环境和基本映像,因此新启动的SBCL可能会比您预期的大。
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.
这篇关于为什么Common Lisp(SBCL)会为一个简单的程序使用这么多的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!