Search code examples
emacslispelisp

Emacs: Performance of keybinding to an anonymous function


My two options are

Define the function before binding

For example:

(defun select-all ()
  (interactive)
  (mark-whole-buffer))

Then binding it:

(global-set-key (kbd "C-a") 'select-all)

Bind anonymous function

Define and bind in one go:

(global-set-key (kbd "C-a")
        (lambda ()
          (interactive)
          (mark-whole-buffer)))

My Question

If I define and bind in one go, is there any performance implication?

References

emacswiki.org - InteractiveKeybinding seems to inform us that it is acceptable.


Solution

  • There is no performance hit with respect to general use of the binding. There may be a small performance hit with respect to other commands which use that information, such as C-h k, but that is also so small it is unlikely you will even notice it and given you probably don't use C-h k that frequently, the most inefficient component in the equation is the user.

    There are two main benefits with defining a funtion and then binding that rather than just doing a lambda

    1. Reuse. Having a named function means you can use it with M-x or potentially use it in other functions or libraries you write.

    2. Documentation. This is an important one. I have often found myself looking at a lambda based key binding and having to work through it to remember exactly what it does. If on the other hand it had been a named function I was binding to, then it would likely have been more obvious. You also get the C-h k stuff and apropos support for a named function.

    I therefore tend ot only use the lambda type binding when it is really trivial and obvious what it is doing and use a named funtion for all other times.