另外猫大的测试比较极端,基本不可能用nth来做表的遍历,比较公平一点是比较随机访问指定数据的效率,代码如下
 - (setq biglist nil
- i -1
- )
- (repeat 10000
- (setq biglist (cons (setq i (1+ i)) biglist))
- )
- (setq biglist (reverse biglist))
- (defun test (func count)
- (setq t0 (getvar "MILLISECS"))
- (repeat count
- (setq x (eval func))
- )
- (strcat "\n返回值" (itoa x) ", 用时" (itoa (- (getvar "MILLISECS") t0)) "ms")
- )
- ;;nth方式遍历表
- (defun ra-nth (lst index /)
- (nth index lst)
- )
- ;;car cdr 方式遍历表
- (defun ra-car (lst index /)
- (repeat index
- (setq lst (cdr lst))
- )
- (car lst)
- )
- _$ (test '(ra-nth biglist 5000) 10000)
- "\n返回值5000, 用时407ms"
- _$ (test '(ra-car biglist 5000) 10000)
- "\n返回值5000, 用时24813ms"
- _$ (test '(ra-nth biglist 1) 10000)
- "\n返回值1, 用时234ms"
- _$ (test '(ra-car biglist 1) 10000)
- "\n返回值1, 用时234ms"
可见数据的位置严重影响结论,当访问表中第一个元素时,nth与car是等效的,当位置越靠近表的后端,则car的效率严重下降(car来实现nth的功能的额外代码开销)。 |