More Conditional Improvements


Passing Conditional Value to Branches

Recently catb0t made an awesome enhancement to conditionals.

Have you ever written code like this?

if thing = some_operation() then

and then people/linters got mad? I use this pattern all the time but it bothers me because it seems like there should be a better way.

Guess what! Now there is. Brat conditionals will pass the result of the condition to the branch:

true? some_operation
  { result |
    p result # prints whever some_operation returned!

This applies to true?, false?, null?, when, and when_equal.

Faster When

This inspired me to go back and look at the performance of when, which I know is abysmal.

You may remember that conditionals can be inlined under common circumstances. This means instead of actually calling the true? function (for example), the code will be converted to a regular Lua if/then. All the overhead for creating closures and calling the functions is removed.

Well, now when has the same super power! And it makes things really fast.

There are a couple example Brat programs which use when heavily.

The first two below are Conway’s Game of Life and Langton’s Ant. I modifed the programs slightly to actually exit and then calculated “frames per second”.

Quicksort uses a random 10,000 element array, so results do vary a little bit.

Example     | Before | After
Life        | 14fps    | 105 fps
Langton     | 2174 fps | 2500 fps
Quicksort   | 0.775s   | 0.085 s
Ackermann   | 0.247s   | 0.022 s

Except for Langton’s Ant, these improvements are huge. Quicksort and Ackermann are nearly 10 times faster!

comments by Disqus
Fork me on GitHub