开发者

Performance of very big classes

I have a class called "simulation" and a method for solving simulation.

class sim
{
    void Step()
    {
    }开发者_StackOverflow中文版

    other methods (20+)...
}

Sim class is only instantiated once during the program.

Step method is called in the order of millions during the program.

Step method uses a lot of local variables (100+). None of those locals are used in other methods.

Is it better to make those local variables a member of the class or keep them as local in Step() for better performance?


It depends. What kinds of variables: primitive types or objects? If the latter, your IL code is still going to chase their pointers. If the former, it depends on what order you access them in, and what CPU you are targeting. Optimizing the layout of variables should come pretty far down the list of performance tuning activities, especially in C# when you're dependent on what assembly your IL is translated into.

As usual with optimizations: first measure performance to identify bottlenecks. Then consider what you can do to remove them. Until you know that you need to do something like that, just write your code as clearly as possible: don't expose local variables unnecessarily by lifting them into the class level. And do consider splitting that Step() method: a large method is hard to understand and therefore even harder to optimize.


As a general rule, you should minimise the scope of variables and only increase the scope if it proves absolutely necessary. Converting locals to member variables is a poor design choice, and thus needs a very strong justification.

Also note that local variables only have a cost if they have non-trivial constructors. A local variable with a noop constructor or no constructor at all has no setup cost, so it would be pointless to expand its scope.


If some of the variables contain objects that can be reused in between multiple method calls, you'd skip the overhead of disposing the old instance and creating a new instance with each method call. For example, lookups in a dependency injection container that won't change in between method calls could be 'cached' in a field.

But aside from that, you probably won't get much of a performance increase. You could give it a try and use a profiler to measure your code performance. A profiler may also help you to identify other bottlenecks in your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜