The 8 pit avoidance points are as follows:
1. Immutability of strings: Create new objects every time you modify
In Java,String
It is an immutable class, which means that once a string object is created, its content cannot be modified. for example:
String str = "Hello"; str = str + " World";
The above code will create multiple String objects, and each splicing will generate a new string and return it, resulting in a waste of memory. Although JVM will help us optimize, a large number of string operations will still affect performance.
Pit avoidance guide: If you need to operate strings frequently, it is recommended to use StringBuilder or StringBuffer. They are mutable and can modify content without creating new objects. For example:
StringBuilder sb = new StringBuilder("Hello"); (" World");
2. Use == to compare strings, full of traps
In Java,==
Used to compare whether the addresses of the two objects are the same, rather than whether the contents are consistent. When we use==
When comparing strings, unexpected results may occur:
String str1 = "Hello"; String str2 = "Hello"; (str1 == str2); // true String str3 = new String("Hello"); (str1 == str3); // false
In the above code,str1
andstr2
is the same string constant, referring to the same piece of memory, butstr3
It is throughnew
The new object created, sostr1 == str3
returnfalse
。
Pit avoidance guide: To compare whether the contents of the string are equal, always useequals()
Methods, for example:
if ((str3)) { ("Equal content"); }
3. String splicing operation: Don’t use it casually + splicing
String stitching is common in daily development, but it is used+
Number splicing strings may cause performance problems. Each time use+
A new one will be generatedString
Objects, especially in loops, are more serious.
String result = ""; for (int i = 0; i < 100; i++) { result += i; // New objects are created every time}
This will lead to the creation of a large number of useless objects, occupying memory and reducing efficiency.
Pit avoidance guide: String splicing in a loop, it is recommended to useStringBuilder
orStringBuffer
. For example:
StringBuilder result = new StringBuilder(); for (int i = 0; i < 100; i++) { (i); }
4. Avoid null pointer exceptions: be careful when using String
It is a good habit to check if it is null before using a string. When calling equals() or other methods directly, if the object is null, a NullPointerException will be thrown.
Pit avoidance guide: You can use () or put a constant string in front of it. for example:
String str = null; ("Hello".equals(str)); // Avoid empty pointers(("Hello", str)); // It's OK
5. Avoid repeated creation of the same string: make good use of intern()
In Java, each string literal is stored in a String Pool. If the same string content is frequently created, it will occupy excess memory. for example:
String str1 = new String("Hello"); String str2 = new String("Hello"); (str1 == str2); // false
even thoughstr1
andstr2
The contents are the same, but they are different objects. passintern()
Method, we can store strings into string pools to improve memory efficiency:
String str1 = new String("Hello").intern(); String str2 = new String("Hello").intern(); (str1 == str2); // true
6. Avoid over-intercepting of String: Use substring() with caution
The substring() method of String creates new string references, which can cause memory leaks if you are not careful, especially when dealing with large strings. Java 7 has been optimized afterwards, but it still needs to be used with caution.
Pit avoidance guide: For intercepting large strings, it is recommended to use new String(substring) to generate new objects to avoid memory leakage.
String largeString = "This is a very large string ..."; String smallPart = new String((0, 10));
7. Pay attention to the performance of ()
()
Although convenient, the performance is low because it involves a lot of formatting operations. In scenarios with high performance requirements, it is not recommended to use it frequently.
Pit avoidance guide: If it is just a simple splicing, no need()
, but useStringBuilder
Or splicing directly faster. If you need complex formatting, then consider using it.()
。
8. Be careful with string segmentation of regular expressions
()
The regular expression engine will be called internally. If it is called frequently, it may lead to performance degradation.
Pit avoidance guide: If the splitter is a simple character, such as a comma or a space, it is recommended to useStringTokenizer
or()
, They are more efficient in simple segmentation scenarios.
Summarize
String
It is a powerful and highly used class in Java, but its immutability, constant pooling mechanism, and various APIs require us to be careful. Mastering the above pit avoidance techniques can help us write programs with higher performance and more elegant code.
The above is the detailed content of the guide to avoid pits using String strings in Java. For more information about using String to avoid pits in Java, please pay attention to my other related articles!