//Option 1:
int _a;
while (_running)
{
_a = _number;
while (_doingWork)
{
//work involving a
}
}
//Option 2:
while (_running)
{
int _a = _number;
while (_doingWork)
{
//work involving a
}
}
EDIT: Took out option 3, I see now that it is irrelevant
Main Questions:
- I am trying to understand which of the above is preferable, and perhaps more specifically how performance is impacted by where you declare and instantiate the variable
- What if these were reference types instead of primitive value types (switch out "int _a" with "Person _a = new Person()"). How would the scenarios differ in terms of performance and which one if preferred?
Additional Questions:
- For primitive value types, does a constructor exist?
- Is there any difference in performance between instantiating a primitive and a regular value type (for example a struct)
Facts:
- int is a primitive value type
- "int a = new int();" is the same as "int a = 0;"
- You can instantiate a value type without the new directive, but that means a default parameter-less constructor is called, so in the case of a struct you must have that constructor in the struct. Moreover, you then have to set each field in the struct by hand
- "new" doesn't imply "create object on the heap" in C# - it just implies "call the constructor". For value types, that doesn't create a new object, it just initializes a new value. (ref: Jon Skeet)
EDIT 2: I found this to be of relevance, if anyone else stumbles accross this question: Difference between declaring variables before or in loop?