Static methods & singleton mode - (excerpt 9cbs forum, Author: hhhh63 (hhhh63))

xiaoxiao2021-03-06  76

From the primary layer, it is mainly two parts after compiling, one is the CPU instruction, which contains various methods; the second is data, that is, various types of variables defined by the program. When you instantiate an object, assign memory as follows: 1. Place static data and static methods in the stack memory when the program starts. 2. Other methods are placed in the code segment for the first time. 3. Place other data in the stack memory each time you instantiate the object. When instantiating the same object, the above 1, 2 items are not moved, just add one item 3. When you destroy an example, if there is still other instances, only the stack data segment of the instance is released (the third item).

According to the above principles, the static methods and data are generally publicity, the extremely common things used for classes, can be called in any place in the program, always occupying the computer memory during the operation of the program, one move use less. If each object in a program uses a database, you can use a static method to connect.

All non-static methods and data can be released when the instance of single-mode mode is destroyed, and if all methods of this class are designed to static, these methods will always occupy memory, waste resources, and not.

When a NEW is an object, just add a data segment and does not reload the method and static variables.

Finally, a variable transmission is said. Many friends on the Internet have said with static variables when they pass the parameters between the answers. I think this method is not good. The purpose of the class is to encapsulate, if you use a global variable Static variables are greatly weakened by parameters.

In fact, the system and applications are quite complicated to memory management. ======================= 下 思 归 文

From the surface, static members can call them directly through class names. Member names, and instance members need to generate an object to be called. The same operation, performance of course static members

However, it is actually related to the object design. Generally speaking the state of the instance of the instance, the call of a method may need to access the status of the current object and change its status, which affects the results of other methods.

Static members are related to class itself, independent of separate instance status. But static members should not be too much, otherwise it is a previous Procedural Programming style, perhaps the object needs to be redesigned or reconstruct.

Static members tend to operate in multi-threaded, need to do synchronization control

转载请注明原文地址:https://www.9cbs.com/read-120707.html

New Post(0)