Re: Quick way to initialize array with all zeros



On Mar 31, 11:59 pm, Patricia Shanahan <p...@xxxxxxx> wrote:
001 wrote:
I want to initialize a large array with 0's... do I have to use a for-loop
or is there some trick to accomplish this?

new int[n] is an all zero int array of size n. If you have an existing
array and need to reinitialize it to zero, use Arrays.fill.

I 'object' to such simplistic answers to what is
effectively a complex question. My first question
for the OP would be, what do you mean by 'quick'?

There are two potential meanings, AFAIU.
1) quick to code.
2) quick to run.

The first is inconsequential, the only point
to writing a shorter method is for the purposes
of code clarity (which has little to do with
'quick').

And for the second, I am not convinced that
Arrays.fill() takes less CPU cycles.

Here is the test code/results I am seeing..
<sscce>
import java.util.Arrays;

class InitialiseToZero {

public static void main(String[] args) {
int length = 10000001;
int[] intArray = new int[length];
long startTimeOfLoop = System.currentTimeMillis();
for (int ii=0; ii<length; ii++) {
intArray[ii] = 1;
}
long endTimeOfLoop = System.currentTimeMillis();

long startTimeOfFill = System.currentTimeMillis();
Arrays.fill( intArray, 0 );
long endTimeOfFill = System.currentTimeMillis();

System.out.println( "Time to loop " +
(endTimeOfLoop - startTimeOfLoop) );
System.out.println( "Time to fill " +
(endTimeOfFill - startTimeOfFill) );
}
}
</sscce>

Time to loop 94
Time to fill 140
Press any key to continue . . .

Time to loop 140
Time to fill 110
Press any key to continue . . .

Time to loop 125
Time to fill 140
Press any key to continue . . .

Time to loop 125
Time to fill 109
Press any key to continue . . .

Time to loop 141
Time to fill 141
Press any key to continue . . .

Out of five runs (Java 1.6 on WinXP on an AMP
XP 1800 CPU), the loop was faster on two
occasions, slower on two, and equal on the
last.

'Six of one - half a dozen of the other.'
as I see it.

Andrew T.

.



Relevant Pages

  • Re: Quick way to initialize array with all zeros
    ... new intis an all zero int array of size n. ... long startTimeOfLoop = System.currentTimeMillis; ... long endTimeOfLoop = System.currentTimeMillis; ... Time to loop 94 ...
    (comp.lang.java.programmer)
  • Re: Quick way to initialize array with all zeros
    ... new intis an all zero int array of size n. ... long startTimeOfLoop = System.currentTimeMillis; ... long endTimeOfLoop = System.currentTimeMillis; ... Why did you fill the int array with 1's in the for loop test ...
    (comp.lang.java.programmer)