林霄云 发表于 2013-12-31 15:47:44

实践检验cons与append生成lisp的耗时差矣

本帖最后由 林霄云 于 2017-8-7 09:48 编辑

一个疑惑或成常识
大家写的常见的代码,包括cad帮助里的示例,在形成列表时,都是采用cons然后反转的思路。天生的append函数为何不用呢?为了弄清白,在q3_2006提供的耗时函数下,我做了如下测试:(defun vtime ()
(* 86400 (getvar "tdusrtimer"))
)

(setq test-time nil)
(setq t0 (vtime));设置起点
;代码块
(setq n 1000)
(setq i 0)
(repeat n
(setq i(1+ i))
(setq test-time (append (list i)test-time))
);n放大系数
;(princ test-time)
;代码块
(princ "\nappend")
(princ (strcat "\n耗时" (rtos (- (vtime) t0) 2 3) "秒"));设置终点

(setq test-time nil)
(setq t0 (vtime));设置起点
;代码块
(setq n 1000)
(setq i 0)
(repeat n
(setq i(1+ i))
(setq test-time (cons itest-time))
);n放大系数
(setq test-time(reverse test-time))

;(princ test-time)
;代码块
(princ "\ncons and reverse")
(princ (strcat "\n耗时" (rtos (- (vtime) t0) 2 3) "秒"));设置终点
结果如下
append
耗时0.047秒
cons and reverse
耗时0.015秒

append
耗时0.031秒
cons and reverse
耗时0.000秒

append
耗时0.032秒
cons and reverse
耗时0.000秒

初步结论:cons是对atom级别的操作,append是list级别的操作,cons and reverse和append效率不在一个数量集上。应该尽量使用cons and reverse。


http://bbs.mjtd.com/xwb/images/bgimg/icon_logo.png 该贴已经同步到 林霄云的微博

gdslqs 发表于 2013-12-31 17:22:40

不错,虽然我经常用cons少用append,但还真没注意这个问题

edata 发表于 2013-12-31 22:45:04

空了试试vla-put-layer和entmod方式才速度比。。

kingcai 发表于 2017-7-26 15:38:13

这是我自己的分析,你看看我说的对不对
http://bbs.ivlisp.com/forum.php?mod=viewthread&tid=35&extra=
我觉得应该是这个原因

xiayuxue213 发表于 2017-7-26 16:42:51

页: [1]
查看完整版本: 实践检验cons与append生成lisp的耗时差矣