DEV Community

Vee Satayamas
Vee Satayamas

Posted on

I have been told to avoid linked lists.

I've been told to avoid linked lists because their elements are scattered everywhere, which can be true in some cases. However, I wonder what happens in loops, which I use frequently. I tried to inspect memory addresses of list elements of these two programs run on SBCL.

CL-USER> (setq *a-list* (let ((a nil)) (push 10 a) (push 20 a) (push 30 a) a))
(30 20 10)
CL-USER> (sb-kernel:get-lisp-obj-address *a-list*)
69517814583 (37 bits, #x102F95AB37)
CL-USER> (sb-kernel:get-lisp-obj-address (cdr *a-list*))
69517814567 (37 bits, #x102F95AB27)
CL-USER> (sb-kernel:get-lisp-obj-address (cddr *a-list*))
69517814551 (37 bits, #x102F95AB17)
CL-USER> (sb-kernel:get-lisp-obj-address (cddr *a-list*))
69517814551 (37 bits, #x102F95AB17)
Enter fullscreen mode Exit fullscreen mode
CL-USER> (setq *a-list* (let ((a nil))
              (push 10 a)
              (push 20 a)
              (push 30 a) 
              a))
(30 20 10)
CL-USER> (sb-kernel:get-lisp-obj-address *a-list*)
69518319943 (37 bits, #x102F9D6147)
CL-USER> (sb-kernel:get-lisp-obj-address (cdr *a-list*))
69518319927 (37 bits, #x102F9D6137)
CL-USER> (sb-kernel:get-lisp-obj-address (cddr *a-list*))
69518319911 (37 bits, #x102F9D6127)
Enter fullscreen mode Exit fullscreen mode

In both programs, the list elements are not scattered. So, if scattered list elements were an issue for these simple cases, you probably used the wrong compiler or memory allocator.

Top comments (0)