Haskell performance

MR K P SCHUPKE k.schupke at imperial.ac.uk
Thu Mar 18 10:56:11 EST 2004

How can you take the results of a comparison like that seriously:

For example the "reverse file" test, here is the Haskell actually used:

main = interact $ unlines . reverse . lines

and here is the C:

/* -*- mode: c -*-
 * $Id: reversefile.gcc,v 1.10 2001/07/20 17:20:32 doug Exp $
 * http://www.bagley.org/~doug/shootout/
 * from Brad Knotwell

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define MAXREAD 4096

int main(int argc, char *argv[]) {
    int nread, len = 0, size = (4 * MAXREAD);
    char *cp, *buf = malloc(size + 1);

    while((nread = read(0,(buf+len),MAXREAD)) > 0) {
        len += nread;
        if(MAXREAD > (size - len)) {
            size <<= 1;
            if((buf = realloc(buf,size+1)) == NULL)
                return(fprintf(stderr,"realloc failed\n"),EXIT_FAILURE);

    if(nread == -1) return(fprintf(stderr,"read\n"),EXIT_FAILURE);

    for (cp = buf+len-1; cp != buf; --cp,nread++)
        if ('\n' == *cp) {
            nread = 0;


Firstly, which of these is more likely to contain an error. A wrong program
scores infinity on the time scale, so Haskell is infinitely faster than a wrong
C program.

Secondly, The C program is using buffers, the Haskell program could use raw IO
and buffers too. If it did it would ba a lot faster, and use about the same
memory as the C code...

In my experiance poor Haskell performance is usually due to not understanding
how the language works (for example head/tail are fast, init/last are slow), or
not using the equivalent techniques in Haskell. To do the equivalent of the C
you could use: http://www.haskell.org/~simonmar/io/System.IO.html


More information about the Glasgow-haskell-users mailing list