GNU bug report logs -
#7174
23.2; `last' can be made faster by using `length'
Previous Next
Reported by: IRIE Shinsuke <irieshinsuke <at> yahoo.co.jp>
Date: Fri, 8 Oct 2010 01:30:03 UTC
Severity: wishlist
Tags: patch
Found in version 23.2
Done: Glenn Morris <rgm <at> gnu.org>
Bug is archived. No further changes may be made.
Full log
View this message in rfc822 format
Recently I saw the implementation of `last' in subr.el and found that
it counts the number of list elements on its own:
(defun last (list &optional n)
"Return the last link of LIST. Its car is the last element.
If LIST is nil, return nil.
If N is non-nil, return the Nth-to-last link of LIST.
If N is bigger than the length of LIST, return LIST."
(if n
(let ((m 0) (p list))
(while (consp p)
(setq m (1+ m) p (cdr p)))
(if (<= n 0) p
(if (< n m) (nthcdr (- m n) list) list)))
(while (consp (cdr list))
(setq list (cdr list)))
list))
So I modified the code to use `length' as follows, and confirmed
it becomes much faster:
(defun last (list &optional n)
"Return the last link of LIST. Its car is the last element.
If LIST is nil, return nil.
If N is non-nil, return the Nth-to-last link of LIST.
If N is bigger than the length of LIST, return LIST."
(if n
(and (> n 0)
(let ((m (length list)))
(if (< n m) (nthcdr (- m n) list) list)))
(and list
(nthcdr (1- (length list)) list))))
Furthermore, the code can be made much simpler (but slower than
the above, in particular cases) as:
(defun last (list &optional n)
"Return the last link of LIST. Its car is the last element.
If LIST is nil, return nil.
If N is non-nil, return the Nth-to-last link of LIST.
If N is bigger than the length of LIST, return LIST."
(nthcdr (- (length list) (or n 1)) list))
Thanks.
IRIE Shinsuke
This bug report was last modified 14 years and 281 days ago.
Previous Next
GNU bug tracking system
Copyright (C) 1999 Darren O. Benham,
1997,2003 nCipher Corporation Ltd,
1994-97 Ian Jackson.