title: Why is this Haskell code so much slower than the C equivalent? Unboxed vectors and bangs already used
body: <p>I wrote a short Mandelbrot Set generator in Haskell and in C and discovered that the C version ran <strong>20x</strong> faster than the Haskell version. While I expected Haskell to be slower, I did not expect more than an order of magnitude considering I am already using unboxed vectors and bangs to avoid excessive thunking.</p>
  
  <p>Profiling reveals that most of the time is spend in the the <code>go</code> function of the following code, which is really just a loop with some comparisons, multiplications and additions.</p>
  
  <pre><code>orbits limit radius a b = go 0 0 0
    where
      r2 = radius * radius
      go !n !x !y
        | n == limit    = n
        | x2 + y2 &gt;= r2 = n
        | otherwise     = go (n + 1) (x2 - y2 + a) (2 * x * y + b)
        where
          x2 = x * x
          y2 = y * y
  </code></pre>
  
  <p>In execution, it takes the C code <em>0.9</em> seconds to run and it takes the equivalent Haskell code <em>18</em> seconds. They both implement the same algorithm and they both generate the same output (PGM graphics file).</p>
  
  <p>The Haskell source code is here:</p>
  
  <ul>
  <li><a href="https://gist.github.com/anonymous/5ff9bb4b9f074df99b3ac9e61175939a#file-main-hs">Main.hs</a></li>
  <li><a href="https://gist.github.com/anonymous/5ff9bb4b9f074df99b3ac9e61175939a#file-mandelv-hs">MandelV.hs</a></li>
  <li><a href="https://gist.github.com/anonymous/5ff9bb4b9f074df99b3ac9e61175939a#file-mandel3-prof">mandel3.prof (profiling report)</a></li>
  </ul>
  
  <p>The C code is here:</p>
  
  <ul>
  <li><a href="https://gist.github.com/anonymous/5ff9bb4b9f074df99b3ac9e61175939a#file-mandel-c">mandel.c</a></li>
  </ul>
  
  <p>What could be the problem that causes this huge difference in performance?</p>