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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With