A few questions about optimizing code for speed in C #

If I have a method that gets called many times, for example:

public int CalledManyTimes(int a, int b)
{
     MyObject myObject = new myObject();
     int c = a + b + myObject.GetSomeValue();

     return c;
}

      

Is there a performance improvement by placing MyObject myObject;

outside the method so it is only declared once, or will the compiler do it automatically?

How exactly are structures conveyed?

I am passing a Point struct to a method (Point only contains int x, int y) and this method changes the value and returns a new Point(newX, newY);

. Is it better to change the Point that was passed to the method and return that? Or I can create Point point

; outside the method suggested in my first question and use that?

+3


source to share


1 answer


myObject

appears to have no beneficial state; like this: make the method static

- 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 everything else: profile.

Looking at your specific questions:



Is there a performance improvement by placing MyObject myObject; outside the method, so it is only declared once, or will the compiler do it automatically?

Zero time initialization is even faster. However, if there is some state that is not obvious in the question, then yes, I would expect it to be more efficient to reuse one instance - however, this changes the semantics (in the original state, it is not shared between iterations).

How exactly are structures conveyed?

By default, they are copied onto the stack as soon as you look in their direction. You can use ref

to avoid copying, which can be useful if the structure is massively overweight or needs to be updated (ideally reassigned rather than modified).

+9


source







All Articles