Analyze the differences between static methods and instance methods

Source: Internet
Author: User

This is a problem that is often raised from time to time. We often think we understand and understand it, but after a deep dive, we find that we do not understand it.

The method is written every day. Many programmers mostly use the instantiation method, but seldom use static methods. The question cannot be answered, or simply answer the difference between the two definitions, the static method can be used only after the new method is used without the new method .... Do we really understand this?

From the perspective of actual project development, there are three methods of development projects:

In the Development Project, BLL and Dal are separated and BLL calls the Dal code.

1. Use static methods in the dal and call them directly without creating instances (this method is probably used by many people)

Class dal
{
Public static string GetUserName (...);
}
Call in BLL:
Dal. GetUserName ();

2. Use the instance method in the dal and use the static member mode (or Singleton) to call the instance:
Class dal
{
Public static readonly Dal = New DAL ();
Public String GetUserName (...);
}
Call in BLL:
Dal. Dal. GetUserName ();

3. Use the instance method in the Dal. Create an instance of the Dal object before each call:
Class dal
{
Public String GetUserName (...);
}
Call in BLL:
Dal = New DAL ();
Dal. GetUserName ();

---------------------------------------------------------------

Development Method 1: I think thread security is suspected in some situations (such as calling multiple databases and GetUserName (...) internal processing operations. This development method does not need new output objects, so it is common.

Development Method 2: most of the applications should be in CS mode, and Dal only has one object in the entire project. If it appears in B/S, I don't think it is compatible with many problems. There are also thread security issues.

Development Method 3: it should be widely used and compatible with various problems, without the suspicion of thread insecurity.

Note: Methods 2 are used in versions earlier than pet3.0 in MS, while Methods 3 is used in both pet3.0 and later versions, in addition, it is clearly explained in the Development instructions. I think we should consider compatibility. In terms of performance, method 2 is not much higher than method 3.

-------------------------------------------------------------------------

I specifically stated, "how do you understand and use static methods and instantiation methods ?" These questions ask a number of programmers who develop different languages (C, C ++, Java, C #)

Their answers are as follows:

Hailong DistrictSaid:

Common methods, and some scattered static methods are generally used

Zhang WeiSaid:
There is almost no difference. If you do not need to instantiate it, you can use the static method. If you want to secure it, you can use the instance method to call other instance methods and variables.

Xiao yuanshanSaid:
Static methods are rarely used, because they are instantiated at startup and occupy resources. Of course, they are useful in combination with the singleton mode.
The principle I want to avoid is to reduce resource consumption.

Zhang XinboSaid:
Static methods mean that I do not need to perform the new operation on the class to which it belongs before calling. I will mainly use static methods in the tool class.

Forward detailsSaid:
Static is the class, and the instance is the object.
The difference between a static method and an instance method is that a static method does not need to depend on attributes in the class and can be closed in this method to complete a function. More instance methods will use the attributes in the class.

Winson _ Zhang LinSaid:
The biggest difference is the memory.
Static methods generate memory at the beginning of the program, and instance methods generate memory in the program running,
Therefore, the static method can be called directly. The instance method must generate an instance first and call the method through the instance. The static speed is very fast, but the memory will be occupied when the instance is too large.
Any language is used for memory and disk operations. As to whether it is object-oriented, it is only a software layer problem. The underlying layer is the same, but the implementation methods are different.
Static Memory is continuous, because it is generated at the beginning of the program, and the instance applies for discrete space, so of course there is no static method fast,
In addition, static memory is limited, and too many programs will not start.

ShowloverSaid:
Static methods and instance methods have their own use...

Whether it is a static method or an instance method, but also depends on the specific situation. For example, the method itself has little to do with the type, you can define it as a static method ..

To use the instance method, you must first create an instance before calling the instance method, but the static method does not need to be ..

In terms of performance, the static method is more efficient, but it will stay in the memory...
In some cases, it is advantageous to use static methods, because for static methods, no matter how many instances you have,
A copy to be maintained in the memory. At the same time, it is more appropriate to use static methods ..

Q. yuyunSaid:
This problem involves many things, such as design patterns. To put it simply, a static method is used to perform a complete stateless operation, while an instance method is opposite. It is usually part of a complete logic and requires certain State values to be maintained.
If we use memory and efficiency to distinguish static method and instance method, we will return to structured programming in the past. The basic starting point for using that method is centered on Object-Oriented.

 

Chen LiangSaid:

The static method is similar to the global function. The instance method is a method in the class.

 

Summary: Everyone has a consensus on this issue: the instantiation method is more used and secure, and the static method is less used.

Sometimes we have some misunderstandings about static methods and instantiation methods.

1. Everyone thinks"The static method is resident in the memory, and the instance method is not. Therefore, the static method is highly efficient but occupies the memory."

In fact, they are all the same. In terms of loading time and memory usage, the static method is the same as the instance method, and the type is loaded when it is used for the first time. There is basically no difference in the call speed.

2. Everyone thinks"The static method allocates memory on the stack, and the instance method is on the stack."

In fact, it is impossible for all methods to allocate memory on the heap or stack. As code, the method is loaded to a special code memory area, which cannot be written.

The method does not occupy more memory. It has nothing to do with whether it is static.
Because fields are used to store information of each instance object, fields occupy the memory, and because the status of each instance object is inconsistent (at least they cannot be considered consistent ), therefore, the fields of each instance object will be copied in the memory, and you can use them to identify which object you are operating on.
But the methods are different. No matter how many instance objects there are, the method code is the same, so there is only one piece of code. Therefore, no matter whether it is static or non-static, only one piece of code exists, that is, only one portion of memory space is occupied.
Why is the same code running different? This depends on the data used by the method. There are two main data sources: one is to pass in through the parameters of the method, and the other is to use the value of the member variable of the class ......

3. Everyone thinks"The instance method can be called only after an instance is created. It is troublesome and the static method is not needed. It is relatively simple."

In fact, if a method has nothing to do with the instance object of its class, it should be static instead of being written as an instance method. Therefore, all instance methods are related to instances. Since they are related to instances, creating an instance is an inevitable step.

Of course, you can write all the instance methods as static, and pass the instance as a parameter. Generally, no problem may occur.

From the object-oriented perspective, when you choose to use the instantiation method or static method, you should determine whether the method has a logical correlation with the instantiated object, if so, you should use the instantiated object instead of the static method. This is only from the object-oriented perspective.

The instantiation method is recommended for thread security, performance, and compatibility.

Why do we need to distinguish static methods from instantiation methods?

If we continue to study in depth, we will leave the technology to discuss the theory. In early structured programming, almost all methods were "static methods". Introducing the concept of Instantiation is something that will happen after the emergence of object-oriented concepts, the distinction between static methods and instantiation methods cannot be simply understood in terms of performance, creating C ++, Java, C # in this way, the introduction of Instantiation methods by object-oriented language Masters does not aim to solve performance and memory problems, but to make development more modeled and object-oriented. In this case, the distinction between static methods and instantiation methods is to solve the pattern problem.

Let us use another example:

For example, in the "person" class, each person has a name, age, gender, height, etc. These attributes should be non-static, because each person has different attributes; but in terms of biology, the subject, category, and so on, this attribute belongs to the whole human, so it should be static-it does not depend on a specific person, no one of them is a "Spine-animal gate Mammal", but a person is a "hoof.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.