Static Vs Instance Method Performance C#

你。 提交于 2019-11-30 01:07:39
SLaks

Your first link states:

Thats because static methods are using locks to be Thread-safe. The always do internally a Monitor.Enter() and Monitor.exit() to ensure Thread-safety

That is utterly, horribly, abominably wrong.


If you add [MethodImpl(MethodImplOptions.Synchronized)] to the method, that statement becomes partially true.

Adding this attribute will cause the CLR to wrap static methods inside lock(typeof(YourClass)) and instance methods inside of lock(this).

This should be avoided where possible


Your second link is correct.
Static methods are a little bit faster than instance methods, because they don't have a this parameter (thus skipping a NullReferenceException check from the callvirt instruction)

I tend to care very little about performance in this respect. What static methods are really useful for are enforcing functional practices. For example if you create a private static helper method in your instance class you have the piece of mind knowing that that method cannot modify the state of the instance.

I personally would always choose the approach that is better for achiving your current task and write stable, readable and easy to maintain code.

There are other ways to improve performance of your application.

some examples:

  • If you want to use a simple method multiple times without instancing an object every time (a helper function) then use a static method in a static class.

  • If your method accesses other variables in the class and is not thread safe use s member function.

  • In asp.net if you want to share an object accross sessions or you can improve performance with a method that internally caches the result a static method would be fine, too.

  • You can mix both ways and use the factory design pattern to have a class with some member functions, but you ensure that there is always only one instance at a time.

  • Sometimes a static function can avoid stupid errors or reduces the need of additional runtime checks:

    String.IsNullOrEmpty(thisstringisnull)  // returns true
    thisstringisnull.IsNullOrEmpty() // If Microsoft would have implemented
                                     // the method this way you would get a
                                     // NullReferenceException
    

But overall it totally depends on the current task. There's no easy "always use this approach..." answer to your question.

This is basically a design choice. If you have logic which include creating instance of class and updating some properties, go for instance method as static method will be shared across the instances. While if you have some utility functions like doing some string manipulation, creating a connection string etc.. which doesn't involve object manipulation, go for static method.

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