Are static methods always held in memory?

前端 未结 2 754
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 18:45

My whole development team thinks, static methods are a terrible thing to use.

I really don\'t see any disadvantages in some cases. When I needed a stateless method befor

2条回答
  •  轮回少年
    2021-02-01 19:20

    There is no distinction between static and instance methods as far as memory is concerned. Instance methods only have an extra argument, this. Everything else is exactly the same. Also the basic way in which extension methods were easy to add to C#, all that was needed was syntax to expose that hidden this argument.

    Methods occupy space for their machine code, the actual code that the processor executes. And a table that describes how the method stores objects, that helps the garbage collector to discover object roots held in local variables and CPU registers. This space is taken from the "loader heap", an internal data structure that the CLR creates that is associated with the AppDomain. Happens just once, when the method first executes, just-in-time. Releasing that space requires unloading that appdomain. Static variables are also allocated in the loader heap.

    Do not throw away the big advantage of static methods. They can greatly improve the readability and maintainability of code. Thanks to their contract, they cannot alter the object state. They can therefore have very few side-effects, makes it really easy to reason about what they do. However, if they make you add static variables then they do the exact opposite, global variables are evil.

提交回复
热议问题