JavaScript-supported maximum recursive invocation number analysis _javascript tips

Source: Internet
Author: User

Are you curious about how many recursive calls a JavaScript engine can make?

How many times recursive calls

The following function allows you to find the answer: (Inspired by Ben Alman's Gist)

Copy Code code as follows:

function Computemaxcallstacksize () {
try {
Return 1 + computemaxcallstacksize ();
catch (e) {
Call Stack Overflow
return 1;
}
}

Three results:

Copy Code code as follows:

node.js:11034
firefox:50994
chrome:10402

What do these numbers mean? Mr. Aleph points out that in V8, the number of recursive calls depends on two: the size of the stack and the size of the stack frame (the local variable that holds the parameter). You can verify by adding a local variable to the computemaxcallstacksize ()-It will return the low value.

Tail invocation (Tail call) optimization in ECMAScript 6

ES6 has tail-call optimization: If the last step in a function is also a function call, it will be "skipped" rather than called by a child function. This means that in ES6 (strict mode), you just change the computemaxcallstacksize function a little bit, and it can go on forever.

Copy Code code as follows:

function computemaxcallstacksize (size) {
Size = Size | | 1;
return computemaxcallstacksize (size + 1);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.