0

I'm currently experimenting with initializing an array of objects, and came across the following two approaches of filling the array of objects:

Approach 1

Cat[] catArray = new Cat[num]
 
for (int i = 0; i < num; i++) {
    Cat someCat = new Cat();
    catArray[i] = someCat;
}

Approach 2

Cat[] catArray = new Cat[num]
 
for (int i = 0; i < num; i++) {
    catArray[i] = new Cat();
}

Is there any tangible difference in the above two ways of initializing and filling an array of objects in terms of memory usage and/or performance?

2
  • Any performant issue would probably be caught by the compiler and reduced so as it remove any overhead. I might use the first approach if I needed to configure the object further, as it's easier to refer to the variable then the array element, but that's personal preference Commented Apr 17, 2021 at 5:47
  • There might be a tangible difference if you live your life in millisecond increments, but there's no practical difference, other than expending your time on premature optimizations. For your example, write code in whatever way is most clearly understandable by both you and your colleagues. Commented Apr 17, 2021 at 5:58

1 Answer 1

1

Objects in Java are always allocated in the heap, whereas their addresses is in the stack.

Thus, using approach 1 or approach 2 does not really make a difference: in approach 1 you are just copying num times more an address. This should not give you any performance issue.

The compiler might even optimize your code and run approach 1and approach 2 equivalently.

From a programming point of view, approach 1 does not really make sense: someCat is never used and it is not accessible after the for loop. In the for loop you can access the new Cat by simply using catArray[i].

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.