nathandemick.com

How many times can you call a recursive function in JavaScript?

Hmm, that's a question you probably have NEVER thought about, amirite? Well, after doing a bit of random JavaScript programming yesterday to help out a co-worker, he expressed concern that the solution I implemented (which used recursion) might have problems if the number of iterations was very large. To be honest, I'd never thought about it before; my ignorance stemmed from the fact that I've never had to deal with a data set large enough to cause a stack overflow from using recursion.

So, is this a valid concern? Should you stop writing recursive functions? After a quick search on Stack Overflow (oh, the irony), I found this answer, which, while old, gives you a general idea of what to expect with modern browsers.

I threw together a quick jsFiddle that you can run in your favorite browser to find out the limits today. The answer's author also put together a test which displays results for multiple browsers, so you can see some more up-to-date numbers.

The end result? Unless you're operating on a data set numbering in the tens of thousands, you don't have to worry about your recursive algorithm crashing. And the sad part is that my co-worker still wanted me to re-write my code.

· 0 comments


Comments