Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

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; i 

Output

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 ms  
java_strings.htm
Advertisements