Understanding Recursion In Javascript And Alternative
Why does my browser slows down when this list data is huge in below code : var list = []; /* Creating some huge dummy data Interstingly, when I change the value of i from 1000
Solution 1:
JavaScript doesn't have tail call elimination. Hence if you loop through a list recursively you'll be wasting a lot of resources. Eventually you might even end up exhausting the stack space.
One possible solution to this problem is to call the tail call asynchronously so that the main function finishes execution before the tail call function begins execution. This ensures that the stack space doesn't increase:
var list = [];
for (var i = 0; i < 10000; i++) list.push(i);
var start = newDate;
nextListItem();
functionnextListItem() {
var item = list.pop();
if (item) {
console.log(item);
setTimeout(nextListItem, 0);
} elseconsole.log(newDate - start);
}
See the following question for more details:
What's the difference between a continuation and a callback?
Edit: A faster solution (as suggested by T.J. Crowder):
var list = [];
for (var i = 0; i < 10000; i++) list.push(i);
var start = newDate;
nextListItem();
functionnextListItem() {
var item = list.pop();
if (item) {
console.log(item);
if (item % 100) nextListItem();
elsesetTimeout(nextListItem, 0);
} elseconsole.log(newDate - start);
}
The loop is more sluggish as it prints to the console in bursts of 100 items. However it completes execution much faster.
Solution 2:
I would suggest to use Javascript Promise for this.
functionnextListItem2 (list) {
returnnewPromise(function(resolve, reject) {
var item = list.pop();
if(item) {
console.log(item);
returnnextListItem(list);
} else {
resolve();
}
});
}
nextListItem2(list);
Post a Comment for "Understanding Recursion In Javascript And Alternative"