This blog has moved to Medium

Subscribe via email

Posts tagged ‘Stackoverflow’

Never rely on tail recursion elimination

Corollary: Never write a recursively method with an unbounded stack depth.

I previously posted a recursive implementation of Factorial, and asked the readers “not to bother saying it’s inefficient because of recursion, since it will probably be optimized away anyway”. Not true.

I don’t really understand why (just posted a question to StackOverflow), but C# does not generally perform tail recursion elimination (at least as my measly test show).

The following method can be easily optimized, both to work faster, consume less space and not to cause a StackOverflowException … but it is not optimized by the compiler (verified by Reflector and the fact a StackOverflowException was indeed thrown).

private static void Foo(int i)
    if (i == 1000000)
    if (i % 100 == 0)

So … if for some reason you prefer writing recursive methods over using loops, do it only where performance is not a consideration and you have a good understanding of the maximal stack depth.

A Good Question

C# programmers – you should read this question and its many answers, I’m sure you’ll learn a thing or two. For example, ThreadStaticAttribute – a clean, type-safe way to get thread local storage in C#.

A few days ago, launched in public beta. I’ve played with it a bit and I think it has the potential to become a great tool for programmers.

It’s basically a combination of blog/wiki/digg/forum. Seems like a most questions get answers (on various degrees of relevance) within minutes-hours. Here are some of the questions I’ve asked, in case you’re interested.

Here’s a review of the beta site (about a month old), but instead of reading it I encourage you to just try it next time you need a programming question answered and Google fails you (don’t forget to subscribe to your question’s RSS feed).