NibblyPig
NibblyPig

Reputation: 52942

A couple of questions about optimising code for speed in C#

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?

Upvotes: 3

Views: 140

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063013

myObject appears to have no useful state; so: make that a static method - problem solved; no allocation, no virtual call:

public int CalledManyTimes(int a, int b)
{
     int c = a + b + MyObject.GetSomeValue(); // static method

     return c;
}

For anything else: profile.

Looking at your specific questions:

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?

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).

How exactly are structs passed around?

By default, they are copied on the stack as soon as you so much as glance in their direction. You can use ref to avoid the copy, which may be useful if the struct is massively overweight, or need to be updated (ideally with reassignment, rather than mutability).

Upvotes: 9

Related Questions