You may be measuring the performance of the garbage collector here - The amount of work the fib
function does is incredibly tiny - it manages to calculate the 100th fibonacci number nearly 6 million times per second! On a 3GHz machine, that would mean it takes around 500 CPU cycles per call, which means it takes approx. 5 cycles per loop body. Considering most instructions actually take more than 1 cycle to complete, this should already be as fast as you can get in a “naive” way (Elm is not exactly known for being close to metal, there is not much we can do).
I made a similar comparison using Benchmark.scale
here, but for the sake of not running into Infinity
, I chose the harmonic instead of the fibonacci series (it works with your original functions as well, I just wanted to avoid floating-point weirdness):
https://ellie-app.com/8fH3hwBNfbfa1
- It takes a while until the runs/second behave like you would expect - runtime does not seem to increase 10x if there are less than 1000 iterations happening
- Starting at around the same point, the runs/second for both versions are roughly the same
So when doing less than 1000 runs, we do not seem to benchmark our function much at all - It’s pretty much just the overhead of calling things in Javascript. The one difference being that the fibLetIn
version also allocates a new function object (“closure”) on the heap on every call, which seems to take the majority of the time if n
is small.