Emacs: Byte Compile Emacs Lisp Files and Auto byte-compile

Buy Xah Emacs Tutorial. Master emacs benefits for life.
, , …,

Byte compiled elisp files will load faster, and also run faster. (by a simple test of a loop, it seems to run about 6 times faster.)

As of today (2013), for init files and light-weight packages, byte compile doesn't make any noticeable speed difference. In general, you should byte-compile lisp package. (example of heavy weight packages that need or must be byte-compiled: js2-mode, nxml-mode, auto-complete-mode.)

If you want emacs to load the byte compiled file if it exists, you should not include the “.el” suffix. ⁖ do it like this (load "my_file"). 〔➤ Emacs Lisp's Library System: What's require, load, load-file, autoload, feature?

How to Byte Compile and Batch Byte Compile

There are several ways to byte compile elisp files. The simplest and most useful are:

Batch Byte Compile Current Dir and Subdir in Emacs

here's elisp code that lets you batch byte compile all elisp files in current dir and subdir.

;; batch byte compile of all elisp (.el) files in a dir and subdirs

(require 'find-lisp)

 (lambda (x) (byte-compile-file x))
  (expand-file-name (concat (file-name-directory (or load-file-name buffer-file-name)) default-directory))

Save above in a file, then run it by calling eval-buffer.

Batch Byte Compile in Terminal

# byte compile emacs lisp files of current dir
emacs -batch -f batch-byte-compile *.el

Auto Byte-Compile Emacs Lisp Files

On problem with compiling init files is this: if you edit a file, you need to remember to compile it again, else emacs will just load the compiled version that doesn't have your changes.

Here's code to make emacs automatically byte-compile elisp when it is saved, but only when byte-compiled file already exists. Put the following in your emacs init file.

(defun byte-compile-current-buffer ()
  "`byte-compile' current buffer if it's emacs-lisp-mode and compiled file exists."
  (when (and (eq major-mode 'emacs-lisp-mode)
             (file-exists-p (byte-compile-dest-file buffer-file-name)))
    (byte-compile-file buffer-file-name)))

(add-hook 'after-save-hook 'byte-compile-current-buffer)

thanks to Adolfo Benedetti for byte-compile-current-buffer.

Like it? Buy Xah Emacs Tutorial.
blog comments powered by Disqus