Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayIndexOutOfBoundsException occurs when using large SSJS array

When I tried to benchmark the difference in execution time between the forward and the reverse loop iteration in server-side JavaScript (SSJS), a (strange) problem occured. While this example code

var i,n=9999;
var arr=new Array(n);
for (i=0;i<n;i++) arr[i]=i; // WORKS
i=n; while (i--) arr[i]=i; // WORKS

works fine, the following code

var i,n=10000; // changed n from 9999 to 10000
var arr=new Array(n);
for (i=0;i<n;i++) arr[i]=i; // WORKS
i=n; while (i--) arr[i]=i; // THROWS ArrayIndexOutOfBoundsException

throws an ArrayIndexOutOfBoundsException for the reverse iteration. The reverse while loop only works fine as long as the array length is lower than 10000. Can anyone tell me what's going on here?

like image 250
xpages-noob Avatar asked Nov 11 '22 02:11

xpages-noob


1 Answers

Not an answer, but as a workaround for such a bug, I recommend using java.util.ArrayList.

var i,n=10000;

var arr=new java.util.ArrayList(n); //changed to ArrayList

for (i=0;i<n;i++) arr.add(i); // changed to .add(value)
i=n; while (i--) arr.set(i, i); // changed to .set(i, value)
like image 113
Serdar Basegmez Avatar answered Dec 12 '22 18:12

Serdar Basegmez