Through a question I posted yesterday, it became clear that declaring a variable outside of a loop and instantiating it inside, has no performance benefits over simply moving the declaration to inside the loop, so declaring and instantiating is done at the same time. But what about instantiation? Consider the two options below.
//OPTION 1:
while (_doWork)
{
Person p = new Person(name = "John", age = 35);
//work that involves reading (not writing to) p
}
//OPTION 2:
Person p = new Person(name = "John", age = 35);
while (_doWork)
{
//work that involves reading (not writing to) p
}
For the purposes of this question, the key assumptions are:
- p is not needed outside of the loop
- p does not get written too (so outcome wise, the two are the same)
- There is no outcome reason for why we should keep re-instantiating p (p looks the same in both options)
Question: Which is better performance wise, and which option is better practice?
The answer to this post (despite being about declaration, not instantiation) seems to indicate the latter: Declaring variables inside or outside of a loop
My Thoughts:
- It just seems like a major waste to me to keep reinstantiating it. Might be okay for primitive types, but for complex classes?
- int a = 0 is the same as int a = new int(), so I guess the answer to the above also applies to primitive types?