0

Which of the following is faster in Java? Is there any other way that is faster than any of these?

int[][] matrix = new int[50][50];

for (int k=0;k<10;k++){
// some calculations here before resetting the array to zero
      for (int i = 0; i <50; i++) {
            for (int j = 0; j <50; j++) {
                matrix[i][j]=0;
            }              
        }
}

Or this:

int[][] matrix = new int[50][50];

    for (int k=0;k<10;k++){
// some calculations here before resetting the array to zero 
          matrix = new int[50][50];
    }
12
  • What does the profiler say? Commented Sep 24, 2012 at 20:41
  • IIRC correctly, Java memory (unlike C) is zeroed when assigned, so the first code would be quicker with int[][] matrix = new int[50][50];. The second code repeats 10 times the same operation, creating 9 useless arrays by the way. Commented Sep 24, 2012 at 20:42
  • The arrays are guaranteed to be initialized with a default value. If you're only zeroing out the array, then declaring/instantiating would be faster. Commented Sep 24, 2012 at 20:43
  • @SJuan76 They are not useless, I want the matrix to be reset to zero. There will be some operation inside for loop before declaring the matrix. Commented Sep 24, 2012 at 20:48
  • 1
    @zesta.. I think second option would be better.. Because it is just creating new Array object every time, thus making the older arrays eligible for garbage collections.. Of course you don't want to iterate 2500 times to set each cells to Zero.. That is done automatically.. Commented Sep 24, 2012 at 20:56

1 Answer 1

2

The fastest way to perform an action that leaves the variable, "matrix" in an equivalent state at the end of a run is int[][] matrix = new int[50][50];

However, none of these solutions are equivalent in terms of number of operations or memory thrash. The statement I've provided is what you are looking for.

Update: With your updated question where you are manipulating matrix and then resetting it.

Your second example will likely be faster on each iteration. The thought being that it is faster to allocate memory than iterate and set a variable 50^2 times. Though this is a question for a profiler. In general, zeroing out memory is something that is better optimized by the JVM than your application.

This being said, it is important to remember than memory allocation is not without caveats in extreme scenarios. If you allocate and trash memory too often, you may have a suboptimal GC experience.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.