I've been doing some experiments and here's something I found. Consider the following C program:
int main()
{
for(int i = 0;
i < 1000000;
++i)
{}
}
and the following Haskell program:
import System.IO
loop :: Int -> IO ()
loop n = if 0 == n then return () else loop (n-1)
main = loop 1000000
Here is the output of time
for the above C program:
real 0m0.003s
user 0m0.000s
sys 0m0.000s
...and for the Haskell program:
real 0m0.028s
user 0m0.027s
sys 0m0.000s
At first I thought that gcc detected an empty loop and optimized it out, but after increasing the number of iterations, the running time of the program also increased. Here are the outputs of time
for both of the programs, with the number of iterations set to 10000000:
C version
real 0m0.024s
user 0m0.023s
sys 0m0.000s
Haskell version
real 0m0.245s
user 0m0.247s
sys 0m0.000s
As you can see, the Haskell program is 10 times slower.
Question is: what is the efficient alternative to the for
loop in Haskell? As we just saw, simple recursion slows the program down about 10 times (and this is probably with the tail recursion optimizations done).