Unlock Java String Performance: Immutability, Pool, and Optimization Tips
This article explains Java's String object characteristics—immutability, constant pool optimization, and final class—while offering practical performance tips such as avoiding split(), preferring StringBuilder over '+' concatenation, and choosing optimal conversion methods for primitive types.
1. String Object
String is a fundamental data type in Java, widely used. Its design includes immutability, constant‑pool optimization, and being declared final, which together improve safety and performance.
1.1 Immutability
Once created, a String's state never changes. This immutability enables safe sharing across threads without synchronization, reducing locking overhead.
1.2 Constant Pool Optimization
When two String variables hold the same literal, they reference the same object in the string constant pool, saving memory. Example:
In the example, s1 and s2 reference the same address (true), while s3 created with new String("123") occupies a different memory location (false). Using intern() returns the pooled reference, making the final comparison true.
1.3 final Definition
The String class is declared final, preventing subclassing and enhancing security.
2. Common String Operation Optimizations
2.1 split() Method Optimization
Although convenient, split() can be slow; combining indexOf() and substring() yields better performance.
2.2 Concatenation Optimization
Using '+' for string concatenation is inefficient. StringBuilder (or StringBuffer when thread safety is required) offers orders‑of‑magnitude faster appends.
StringBuilder is preferred when thread safety is not a concern; otherwise, use StringBuffer.
2.3 Primitive to String Conversion
Converting primitives via String.valueOf(), concatenation with "", or calling toString() have different speeds. Direct toString() is fastest, followed by String.valueOf(), while using +"" is slowest.
Therefore, avoid +"" for conversion and prefer the primitive’s own toString() method.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
