Criterion for benchmarking Haskell programs

2018-03-21

It’s been bothering me for a while now that I don’t know the most efficient way to append/concatenate strings in Haskell. I thought that this might be an interesting motivation for learning how to use Criterion.

The standard way

Here’s the first version of the function I want to test:

This is pretty standard stuff: I want to build a string in left-to-right order. It uses the append operator, ++.

Using concat

Here’s another variant using concat:

Using ShowS

And another using showString from ShowS:

Using Seq

And, finally, using sequence which supports O(1) append to either end of the sequence:

The program

Here’s the whole program:

This depends on the following non-base packages:

Here’s a full, working project if you like.

I run it using stack as follows:

stack clean
stack build
stack exec -- concat-vs-append --output bench.html

The results

You can view the output from the program here.

The conclusion

Use ++, concat or ShowS, it really makes no difference. Don’t use Seq. I will need to analyse further to make sure that this is a meaningful test. See you later!

Tags

Haskell
Criterion

Content © 2024 Richard Cook. All rights reserved.