157 suggestions for writing high-quality code to improve C # programs-recommendation 100: there is no difference between static methods and instance methods,
Recommendation 100: there is no difference between the static method and the instance method
The static method is identical to the instance method in terms of the loading time and memory usage. Here, we first introduce the concept "type object ". For example, we all know that new Person () will generate an object called "Instance Object", which will be loaded to GC Heap at runtime. The "type object" refers to the object that represents the Person type. This object is loaded to Loader Heap when the type is used for the first time. Type objects include their own pointers, their own fast synchronization indexes, static fields, and a method table. In this method table, both static methods and instance methods are stored. Of course, method record items are stored, and the methods are compiled at runtime during calling. The distribution of type objects and instance objects in the memory is as follows:
The only difference between static methods and instance methods is that when we need to use instance methods, we should first have instance objects. We cannot bypass the Instance Object and directly call the instance method from the type itself. Therefore, from the design perspective, if a method only has a relationship with the type itself, it should be designed as a static method. If it has a relationship with the type of instance object, then it should be designed as an instance method.
Static methods are misunderstood by many people: static methods are naturally synchronous methods. Even programmers with some development experience sometimes make such common sense mistakes. Although Microsoft claims that most of the Code in FCL has been implemented as thread-safe, it does not mean that the code is naturally synchronized. To secure the static method thread, the programmer must write the Synchronous Code, instead of letting the compiler or runtime do these things for us.
We need to understand static methods and instance methods from the design perspective. Without the design, there is no difference between them.