Mutable String and Emacs Buffer Passing Style

Speaking of Christopher Wellons, he's got a very interesting post over at null program on mutable strings and Emacs buffer passing style. Wellons starts by pointing out that strings in Emacs Lisp, like many other languages, have a fixed size and any operation that changes the size requires that a new string be allocated and current content copied into it. That can be a problem when you're building up a string incrementally. Next, he observes that Elisp has a natural character-oriented data structure: buffers. Why not use a buffer to build up the string components and then turn the buffer into a string with buffer-string. Something along the lines of:

(with-temp-buffer
  ;; build up the string
  (buffer-string))

That's a good tip all by itself but Wellons goes further.

Suppose you are writing a function to construct a string. A natural technique is to have the function build the string in a buffer and then pass the buffer back to the caller who can do whatever they need with it (perhaps never coercing it into an actual string). The problem is that using that method makes it easy to leak buffers, which are not garbage collected. Wellons has a nice example of how that can happen in his post.

To avoid this problem, Wellons advocates what he calls a buffer passing style. With this approach, a buffer is implicitly passed to the function, which fills it with the desired data. “Implicitly” because the caller arranges for the current buffer to be the buffer that the function uses. Then the caller can kill the buffer after using the data. The actual idiom is something like:

(with-temp-buffer
  (fill-buffer-with-desired-data)       ;string building function
  ;; process the data
  )

This is nice because the with-temp-buffer macro takes care of killing the buffer when you reach the end of the macro body.

Take a look at Wellons' post. It's very informative and gives some fleshed out, realistic examples rather than the skeletons I give here.

This entry was posted in Programming and tagged , . Bookmark the permalink.