Avoiding stack overflow by using setTimeout

后端 未结 3 836
耶瑟儿~
耶瑟儿~ 2021-02-09 20:42

I\'ve found the following question here:

The following recursive code will cause a stack overflow if the array list is too large. How can you fix this a

3条回答
  •  感情败类
    2021-02-09 21:09

    The repeating for loop is the most efficient for the code posted. However, if your actual code cannot be fitted to using a for loop, then there is another alternative.

    The use of setTimeout depends on your opinion of 'practical,' so let's just list the facts so you can decide for yourself.

    • setTimeout forces the browser to swamp the CPU with operations to get millisecond precision timing. This can be very power inefficient.
    • With setTimeout, every iteration will cost 4ms. Just 4 iterations will take the time for a whole frame to get rendered. 250 iterations, and a whole second goes by.

    But there is an alternative to setTimeout that will help you achieve exactly what you are trying to do without using setTimeout: the DeferStackJS library. If you use DeferStackJS, then all you would need to do is as follows.

    var list = readHugeList();
    
    var nextListItem = function() {
        var item = list.pop();
    
        if (item) {
            // process the list item...
            DeferStack( nextListItem );
        }
    };
    

    Please emphasize that the above snippet of code is intended for demonstrating how to integrate DeferStackJS. Truth be told, using either DeferStackJS or Array.prototype.pop would be very inappropriate for this specific snippet of code. Instead, the following code would beat both of them hands down.

    var list = readHugeList();
    
    var nextListItem = function() {
        "use strict";
        var item, i = list.length;
        while (i--) { // Bounds check: as soon as i === -1, the while loop will stop.
                      // This is because i-- decrements i, returning the previous
                      // value of i
            item = list[i];
            if (!item) break; // break as soon as it finds a falsey item 
            // Place code here to be executed if it found a truthy value:
    
            // process the list item...
        }
        if (i !== -1) {
            // Place code here to be executed if it found a falsey value:
    
        }
    };
    

    The only reason DeferStackJS is mentioned is because I am a firm believer in that the #1 duty of a person answering a forum is to answer the original question asked. Then after they answer that they can put up commentary second-guessing the question about what was intended to be asked like this.

提交回复
热议问题