Performance Optimization: == Replace Equals

xiaoxiao2021-03-06  44

Many people must think that this topic is old, and some people who have a little bit is more mentally, there is nothing to discuss, because this problem is discussed too much. However, since you come in, you may wish to finish it, just give a face, a few minutes, maybe you will be a little inspiration!

I haven't written something for a long time. Most people don't care about the efficiency of the program, because the CPU is always idle, the memory is always empty. Many people think that for basic types ==, use equals () for reference types (), why?

For reference types, if you can use == instead of Equals (), you can greatly improve efficiency. Needless to say, we don't care about efficiency! But if you can increase 100 times or even 1000 times, you don't care, then you don't have to look down.

Only two cases:

1. How to determine if a class specified If you think of instanceof, you still don't make it, but here you can't use instanceof, here you judge whether String is an example. Given a Class C, it is determined whether it is a Class method for String class 1: Boolean B = C.GetName (). Equals (String.class.getName ()); Method 2: Boolean B = (c == String.class) The first method is too bad, the second method is at least 100 times, or even 1000 times or 10,000 times, because == almost no time we know the comparison of the string is a character comparison. Conclusion: For comparisons that can be used ==, do not use equals (); general single-size instances can be used ==, such as enumeration classes.

2. For strings to use == instead Equals ()? Since == efficiency is so high, and string is a non-variable, can you use == instead of Equals? String S1 = "Hello"; String S2 = "Hello"; Boolean EQ = (S1 == S2); This can of course use == instead, because they are the same object, but if you use new, you can't .. Strings Never use new generation if you can use == instead of Equals? Still not, one example: string s1 = "hello"; stringbuffer sb = new stringbuffer (S1); string s2 = sb.toString () Boolean B = (S1 == S2); // False Conclusion: Specific occasion can be used == instead, because most cases cannot be used ==, so unless performance is too important, do not use == instead of Equals, because you This may not understand this. 3. Is it really easy to use? See the efficiency of == so high, I have been using it, I will change: Boolean EQ (String S1, String S2) {S1 = S1.InTern (); S2 = S2. INtern (); Return S1 == S2;} It can think of this is really not simple, but not only does not improve efficiency, but it greatly reduces efficiency. Because INTERN itself is slower than Equals, you are still twice! However, this usage I have seen in the Class class code.

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

New Post(0)