4

I've noticed that some people use a t at the end of this code:

(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)

that t makes it append at the end of the list instead of the beginning.

Why is that? Is it faster for Emacs Lisp add-to-list function to append at the end than at the beginning?

1 Answer 1

6

No, it is always faster to add in the beginning (except that add-to-list has to scan the whole list anyway - as pointed out by @phils in a comment).

However, performance is never an issue with add-to-list which is only used to customize user options like package-archives and auto-mode-alist.

The reason to add to the end of an alist is to avoid disturbing existing settings.

E.g., I had

(add-to-list 'auto-mode-alist '("\\.ts\\'" . js-mode) t)

so that *.ts files would be edited in javascript mode, but I added it to the end so that as soon as Emacs came up with its own default mode, it would be used instead of js-mode (actually, Emacs uses js-mode for now but you got my point)...

1
  • 5
    Note in particular that performance isn't an issue because add-to-list only adds the list item if it's not already there, so it must check the entire list for a match regardless of where it's going to add to. If it reaches the end of the list without finding a match then it has a handle on both the beginning and end of the list, and adding the item in either position is trivial at that point (whereas if you only knew about the start of the list, pushing to the start would be faster).
    – phils
    Commented Mar 14, 2023 at 23:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.