Does javascript performance suffer from deep recursion?

余生颓废 提交于 2019-12-23 04:06:17

问题


I've written a javascript to emulate WPF DockPanel Layout behaviour in HTML through the help of javascript.

Now i'm running into performance issues once i begin nesting those panels to a recursion level of 10. Oddly enough it's nothing more than ordinary recursion and on the deepest level the function in question is finishing in between 0,2 and 2ms.

Now either i do have some ghost performance loss, or is there a massive cost in invoking recursion for javascript? I hope one of you knows.

If there's a cost the obvious solution would be recursion unrolling which would be rather sad.

I've read SO-Recursive function calling in JavaScript On this, but does that really mean that i may have to accept recursiondepth n = functioncost * (10^(n-1)) for every depth of recursion i'll go?

Also this (which refutes the idea of recursion beeing slower than iteration) SO - Is iteration faster than recursion, or just less prone to stack overflows?

And this Programmers: Performance: recursion vs. iteration in Javascript, which speaks for iteration beeing faster than recursion by a factor of 4 (sigh...)

This is a general question, independant of browser JS engine. If you know about it beeing slow in one but fast in another that information would be welcome too. I was assuming that it would be the same in all.

Wrapup information for visitors: The impact of recursion vs iteration is very significant. Iteration in general wins.

  • Factor FF30 : 5~
  • Factor Chrome 36: 40~
  • Factor Native IE8, WinXP: 10~

回答1:


Yes, the recursion has a very big impact on performance in JavaScript, always avoid it, use only iterative approach

A simple example of fibonacci function (recursion vs loop):

http://jsperf.com/fibonacci-recursive-or-iterative/4

Another example written by me some time ago (object navigation):

http://jsperf.com/object-navigation

var a = {
    b: {
        c: 'd'
    }
};

find(a, 'b/c'); // => 'd'

OP-Test: http://jsperf.com/iterative-vs-recursive-method-invocation/3



来源:https://stackoverflow.com/questions/24915428/does-javascript-performance-suffer-from-deep-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!