Limitation of Array.prototype.push.apply under V8 for Google Apps Script

Gists

Description

When V8 is enabled, Array.apply has the limitation for the number of elements. When it is over the limitation, an error like RangeError: Maximum call stack size exceeded occurs, while the issue didn’t occur when V8 is disabled. In this case, this issue occurs at both Google Apps Script and Javascript. So please be careful this.

Sample situation

For example, when Array.prototype.push.apply is used for combining the arrays because the process cost of Array.prototype.push.apply is lowest of 3 patterns of Array.prototype.push.apply, Spread syntax and concat, please be careful above issue. Ref

Please see the following script.

let ar1 = [];
const ar2 = Array(125859).fill("sample");
Array.prototype.push.apply(ar1, ar2);

When above script is run, the error of RangeError: Maximum call stack size exceeded occurs at Array.prototype.push.apply(ar1, ar2);. But when const r = Array(125858).fill("sample"); is used, no error occurs. On the other hand, the following script is used, no error occurs.

let ar1 = Array(1000000).fill("sample");
const ar2 = Array(125858).fill("sample");
Array.prototype.push.apply(ar1, ar2);

Summary

From above sample scripts, when the array is combined using Array.prototype.push.apply(ar1, ar2), it is found the following points.

References

 Share!