The first two days enough OH year company training, said the coding optimization. Now the preliminary summary: (some are not sure to talk about it)
- Multiple string concatenation (especially in the loop), it is advisable to use the Stringbuilder.append () method, less string +, as for string. Format () is more resource-less. Of course, if the string concatenation is small, within 3 times, that also casually, in order to beautiful string. Format () is also available.
- String. The essence of Empty is "", reflector decompile string. Empty result: public static readonly string Empty = ""; So string. Empty and "" can be considered the same.
- Equals () and = = Do not. "All classes in Java are inherited from the base class of object, and a method of equals is defined in the base class of object, and the initial behavior of this method is to compare the memory address of the object, but in some class libraries This method is overwritten , such as String, Integer,date in these classes equals has its own implementation, and is no longer a comparison class in the heap memory of the storage address. " So, for the int equivalent type and string, Equals () is no different than = =. For reference types, use Equals () as much as possible, especially if you implement equals () yourself.
- The nature of the using () is try{}, finally{}, and the compiler writes close (), Dispose (), and so on in finally{} to release resources. The following code:
- string s = String. Empty;using (StreamReader sr =new StreamReader (@ "C:\\a.txt")) {s = Sr. ReadToEnd (); }console.writeline (s);
- Anti-compile IL results:
- So there is no need to write close (), Dispose (). using{} Similar to syntax sugar, which is a mixture of code in using{}.
- Another mention, in try{return xx;} catch{return xx;} A return in finally{} will appear in a strange order of execution, not necessarily returned in try{}, and may have to be executed finally{}. Therefore, it is more safe and clear that we should return to the end after the unification of finally{}.
. Net using,string. On empty