Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active Apr 20, 2020
Embed
What would you like to do?
Limitation of Array.prototype.push.apply under V8 for Google Apps Script

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

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.

  • When you want to combine the array with the small size (for example, it's in the for loop.) with V8, Array.prototype.push.apply is suitable.
  • When you want to combine the array with the large size is combined with V8, Spread syntax is suitable.
  • When you want to combine the array with the large size (for example, it's in the for loop.) without V8, Array.prototype.push.apply is suitable.
  • When you want to combine the array with the large size (for example, it's in the for loop.) with and without V8, concat is suitable.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment