Do C# static functions perform better than nonstatic functions, beyond reduced memory usage?

夙愿已清 提交于 2019-12-02 17:00:45

From Static Classes and Static Class Members (C# Programming Guide)

A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.

Aside from what astander said, your question suggests a misunderstanding of what instance methods do. Regardless of whether the function is static or not, there is only one copy of the function code in memory. A non-static method has to be called through an object, but the object does not carry its own private copy of the method. So the memory usage of static and non-static methods is in fact identical, and as others have pointed out, the performance characteristics are nearly identical.

Non-static member variables, however, do exist separately for every object that you create. But it is nearly always a waste of time to worry about that memory usage, unless you actually have a memory-related problem in your program.

This is a little bit off-topic, but none the less important.

The choice of making methods static or instance should not be based on execution time (which anyway seems not to matter). It should be based on whether the method operates on an object. For instance, all the Math.* methods are static while e.g. (most) String.* methods are instance since they operate on a String instance. My personal philosophy: a good design should make up for the few cycles that may be saved elsewhere.

Another view on the subject: I recently worked with a guy who had been told that static methods are evil because they take us back to the dark age of procedural programming and thus shall be avoided at all costs. This resulted in weird examples of classes that required instances for access to methods that had absolutely no interest in the internals of the object.

Phew, it felt good to get that from my hearth.

Mike Dunlavey

Good answers - basically it doesn't matter, which is the answer to nearly every question of this sort. Even if it did make a difference - If execution time of your program cost a dollar, this sort of issue is likely to cost a fraction of a cent, and it is very likely that there are other things costing a great deal more.

MeasureIt to be certain, but you'll find unless you're creating a globe-spanning ultra-high-volume transaction processing supercomputing cluster, it's not going have an appreciable difference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!