So, I posted a story about Fibonacci sequences and noticed that the recursion in PowerShell is really rather slow. But I also noticed something interesting — I had expected that recursing using a function would be a little cheaper (and faster) than recursing using the pipeline, and it turns out that it’s not. At all.
I’d love to hear some thoughts on why I got the speed results I got here. At first I thought it was something about type coercion, but as you can see, I tried casting everything to no avail. There’s no difference if I don’t output anything, and in fact, the non-recursive algorithm can trivially output every Fibonacci number in the sequence without affecting it’s time (I actually altered it so it didn’t to keep the output clean).
Obviously I expected the recursive algorithms to be slow and scale badly because of the amount of work involved, but how is it that the pipeline-recursive “filter” outperforms the plain old recursive function (albeit by an infinitesimal fraction)?
P.S.: The numbers in braces with the colon (like [18]: ... ) is my prompt.
Scott Hanselman has been posting weekly snippets of code in various languages … today he did Fibonacci sequences … by the way, the point of his posts is to get you to read code in other languages, not necessarily showing the best way to do things in any of the languages represented — you only solve fibonacci sequences recursively in demos, not in real life. Well, except perhaps in tightly optimized tail-recursion languages, maybe in Haskell …
That’s just beautiful
... incidentally, by default, PowerShell will only recurse up to 100 levels in the stack, so it kind-of sucks at recursive calls. You could also write that as a traditional function in powershell, but the way powershell passes arguments to functions makes it really awkward. I’ll put it on multiple lines so you can read it easier.
As a side note, that function actually runs measurably slower than the pipeline method … but speeds up noticeably if you stick a few [int] type specifiers in the right places so PowerShell doesn’t have to infer types — something to think about.