
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to Optimize String Creation in Java
The String creation can be optimized to reduce memory consumption and improve performance. Using the String.intern() method in Java makes sure that identical string values share the same memory reference. It avoids the creation of multiple objects for the same value.
Optimizing string creation
When a string is declared, a single copy is stored in the JVM string pool. If the string is interned, Java checks the pool for an exact match. If it finds the string, it reuses the existing reference; if not, it adds the string to the pool. This string.intern() method also save memory when many strings with the same value are used, as only one copy is stored in memory.
Syntax
The following is the syntax for Java String intern() method
public String intern()
Java program to optimize string creation
The following example optimizes string creation by using String.intern() method.
public class StringOptimization { public static void main(String[] args) { String variables[] = new String[50000]; for( int i = 0; iOutput
Creation time of String literals : 0 ms Creation time of String objects with 'new' key word : 31 ms Creation time of String objects with intern(): 16 msjava_strings.htm