If I have a method that is called many times, such as:
public int CalledManyTimes(int a, int b)
{
MyObject myObject = new myObject();
int c = a + b + myObject.GetSomeValue();
return c;
}
Is there a performance boost by putting MyObject myObject; outside of the method, so it’s only declared once, or will the compiler do this automatically?
How exactly are structs passed around?
I’m passing in a Point struct to a method (Point contains only int x, int y), and that method is altering the value and returning a new Point(newX, newY); Is it better to alter the Point that was passed into the method and return that? Or can I create a Point point; outside the method as proposed in my first question and use that?
myObjectappears to have no useful state; so: make that astaticmethod – problem solved; no allocation, no virtual call:For anything else: profile.
Looking at your specific questions:
Initializing it zero times is even faster. However, if there is some state that isn’t obvious in the question, then yes, I would expect it to be more efficient to reuse a single instance – however, that changes the semantic (in the original the state is not shared between iterations).
By default, they are copied on the stack as soon as you so much as glance in their direction. You can use
refto avoid the copy, which may be useful if the struct is massively overweight, or need to be updated (ideally with reassignment, rather than mutability).