Reputation: 197
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];
}
Upvotes: 0
Views: 360
Reputation: 1388
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.
Upvotes: 2