Asp tutorial. net c # string and stringbuffer
Key Points
1). simply think that. append () is more efficient than "+" is wrong!
2). Do not use new to create a string.
3). Note the use of intern ().
4). When the string value can be determined during compilation, "+" is the most efficient.
5). Avoid using "+ =" to construct strings.
6) when declaring the stringbuffer object, specify the appropriate capacity. Do not use the default value.
First, we must be clear that the string class is of the final type, so you cannot inherit this class or modify this class. It is very simple to use string, usually string s = "hello", but a constructor string (string s) is provided in java api ), therefore, you can also use string s = new string ("hello") in this way. It is not recommended to initialize a string later, because the new operator means that a new object will be generated on the heap. If such an operation occurs in a loop, the cost is heavy. For example
For (int I = 0; I <1000; I ++)
{
String s = new string ("hello ");
}
This will create 1000 string objects. Because the string class is final, such an operation actually generates a new string object each time. If you use string s = "hello"; then you can reuse it. Why is it reusable? The following explains:
String s = "hello ";
Jvm first searches for Objects Based on the content "hello". If no object is found, it creates a new object in heap and assigns it to s1. Otherwise, it uses an existing object.
String s = new string ("hello ");
Jvm directly creates a new object on heap. Therefore, a string object with the same content and different addresses will appear in heap.
Stringbuffer generates a piece of memory space, and all related additions, deletions, and modifications are performed on this Scalable Memory. Therefore, it optimizes the consumption of memory space, especially in loops.
Efficiency: string and stringbuffer
Scenario 1:
(1) string result = "hello" + "world ";
(2) stringbuffer result = new string (). append ("hello"). append ("world ");
(1) The efficiency is better than (2). Don't be surprised because jvm will do the following processing:
String result = "hello" + "world ";
String result = "hello world ";
1 2