Reputation: 71
I'm making a yahtzee game in java, and I have a variable called frequencyCount which is an array keeping track of how many die there is of each one. I reset this array after each roll with a for loop setting each index to 0.
for(int i = 0; i < frequencyCount.length; i++) {
frequencyCount[i] = 0;
}
But is there any problem with just creating a new array each time like this:
frequencyCount = new int[6];
The reset method will be called 45 times per player per game.
Which way is best? Is it a problem to keep creating new arrays, or doesn't it matter since this is a small game?
Upvotes: 0
Views: 135
Reputation: 8662
both ways are almost identical, new int[] also uses for loop to make all of them zero (optimized) but will throw the old array and make the GC work, so both ways almost identical
Upvotes: 1
Reputation: 166
I agree with Dima; both methods produce the same result. I would say to use the second because it requires fewer lines of code. There is no need to create new arrays when one will suffice.
Upvotes: 0
Reputation: 30138
In practice you will not see any difference, you shouldn't worry too much about performance in cases like this. Focus on keeping your code clean and readable, and I believe method no. 2 is more concise.
Upvotes: 5