Increasing stack size in browsers

允我心安 提交于 2020-02-23 10:43:28

问题


Short question: I have a javascript that goes very deep in recursion. How can I increase the stack size so that I can execute it (something like "ulimit -s unlimited" in Unix systems)?

Long story: I have to draw a graph and I use Cytoscape JS (http://js.cytoscape.org/) coupled with the Dagre layout extension (https://github.com/cytoscape/cytoscape.js-dagre). The drawing algorithm goes deep in the recursion and I end up getting "Uncaught RangeError: Maximum call stack size exceeded" in Chrome and "too much recursion" in Firefox. How can I set the stack size to unlimited or very large (i.e. like "ulimit -s unlimited" in Unix systems) so that I can draw the graph?

Thank you!


回答1:


You cannot alter the stack size in browsers, but you can use a trick called trampolining.

You can find a working code solution here:

How to understand trampoline in JavaScript?




回答2:


Try changing your algorhythm to not use as much stack space on each iteration of the function. For instance:

  • Setting local variables to null when not being used.
  • Use global variables for temporary calculations when possible. That way, that temporary variable won't be on the stack.
  • Use fewer variables in your recursive function. Reuse the same variables for different things in different parts of the function.
  • Break your recursive function into several functions. Some of those functions won't be recursive and therefore the local variables in those functions won't carry on when the recursive function calls itself.
  • Create a global array of things to do and add items to this list instead of calling a function recursively. use the push and pop methods of the array() object.
  • Have fewer parameters on your recursive function. Pass an object instead.

I hope these ideas help you.




回答3:


Chrome has a flag for this:

chromium-browser --js-flags="--stack-size 2048"

You will also want to run ulimit -s unlimited before running the command above, though: otherwise, your deeply recursive Javascript code will crash Chrome.



来源:https://stackoverflow.com/questions/35380984/increasing-stack-size-in-browsers

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