# Well, I guess sometimes you just need stuff being mutable

I’ve been generating some prime numbers in Clojure lately, and I was struggling to get decent performance when working with “idiomatic” immutable sequences. I’ve started with a naive implementation of a lazy prime sequence:

It took over a minute to compute all the primes under 200’000, and over 2 hours to crunch till 2’000’000. Then, I went for Sieve of Eratosthenes:

Here, n = 200’000 took 24 seconds, and n = 2’000’000 — 44 minutes. Kind of an improvement, right? By the way, mind the “doall” at the last line. If you remove it, the poor thing dies from heap overeating, when lazy “filters” stack on top of each other long enough.

Still, 44 minutes for a 2’000’000-limit? That sounds just too slow. Therefore, I wrote a quick and dirty sieve function in PHP, and verified I’m getting the same results by checking the numbers’ sum:

Time to find all the primes under 2’000’000? Two freaking seconds. If you bother writing this in C, you may shrink it down to under 100 ms, I’m sure.

Wait, but what if I do need generating primes fast in Clojure? And the answer found me*

It’s a sieve-with-hints function written by someone under the moniker “rhickey” ;) and it uses… Java arrays, reaching 2’000’000 limit in about a second.

So, that’s how I learned to stop worrying and love mutable arrays.

**My original source http://paste.lisp.org/display/69952 is no longer available. See it
at Archive.org*