[racket] Tutorial: writing a language (brainf*ck) in Racket

From: Sam Tobin-Hochstadt (samth at ccs.neu.edu)
Date: Mon Jun 20 14:02:34 EDT 2011

On Mon, Jun 20, 2011 at 1:46 PM, Danny Yoo <dyoo at cs.wpi.edu> wrote:
> In more detail: the key performance issue was the inefficient use of
> parameters.  I had wanted to make sure I was using a fresh state per
> module, so I had set up a parameter called 'current-state' that was
> parameterized over the body of the module.  It turns out that this is
> not an efficient way to scope the state to the module's body.  As an
> alternative, I replaced this with a use of the syntax-parameterize
> form in the racket/stxparam library, and that improved performance
> quite a bit.

Since you're in total control of what modifies the state, you can also
use the various operations from `racket/unsafe/ops'.

You'd want to do the following:
 - add some bounds checking in `increment-ptr' and `decrement-ptr'.
 - change the `vector' operations to their `unsafe-vector' counterparts.
 - change `sub1' and `add1' to use `unsafe-fx+' and `unsafe-fx-'
 - change `=' to `unsafe-fx='
 - change the uses of `set-state-ptr!' and `state-ptr' and such to use
`unsafe-struct-set!' and `unsafe-struct-ref'.

All of those will almost certainly improve performance.

Other ideas:
 - defining the semantics functions as macros, to produce inlining.
 - lifting out the definition of the state vector and pointer to the
top level, so that you don't have to reference the state all the time.

Those I'm less sure will improve performance.

It would be even better if you wrote it up as an optimization section.  :)
sam th
samth at ccs.neu.edu

Posted on the users mailing list.