r/brainfuck • • 1d ago

Compiler optimization techniques?

I finished writing a (really crude) brainfuck JIT not too long ago and while I'm pretty pleased with its speed, I'm still thinking of ways I could make it faster. I already thought of reducing chains of unary arithmetic instructions like +, -, <, and > into a single instruction, and I'm thinking of reducing [-] into something along the lines of tape[datapointer]=0 because it seems to be a fairly common construct in the programs I've found on the internet.

What else can I do to make my interpreter faster? Are there any low-hanging fruits left to pick?

2 Upvotes

3 comments sorted by

2

u/danielcristofani 1d ago

Turning chains of [[[[[ or ]]]]] into one instruction is one I always suggest. Then the next big step up is eliminating loops with balanced >< that run off a counter, like [<<++>>>-<-].

2

u/Just_Feedback9220 1d ago

Ooh, clever! I never would have thought of your first suggestion and your second is pretty much a way better extension of my second idea.

Also thank you for writing so many of the programs I tested, they're all insanely impressive! :)

1

u/vintagecomputernerd 17h ago
  • Pattern matching for common idioms. You already mentioned [-], but there are other common idioms for move/copy/multiplication
  • Partial evaluation. If a part of a program only relies on data known at compile-time (ie no decision on i/o operations), you can precalculate everything. Some bf compilers can transform a hello world program into basically print "hello world"
  • convert to an immediate language like LLVM IR, and let llvm do optimizations for you.

There was a nice blogpost about a bf compiler that used pattern matching and a llvm backend, and, interestingly, the combination of pattern matching and llvm optimizations had better performance than each separately