- Java Programming Examples
- 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 Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to optimize string creation in Java
Problem Description
How to optimize string creation?
Solution
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 < 50000; i++) { variables[i] = "s"+i; } long startTime0 = System.currentTimeMillis(); for(int i = 0; i < 50000; i++) { variables[i] = "hello"; } long endTime0 = System.currentTimeMillis(); System.out.println("Creation time" + " of String literals : "+ (endTime0 - startTime0) + " ms" ); long startTime1 = System.currentTimeMillis(); for(int i = 0; i < 50000; i++) { variables[i] = new String("hello"); } long endTime1 = System.currentTimeMillis(); System.out.println("Creation time of" + " String objects with 'new' key word : " + (endTime1 - startTime1) + " ms"); long startTime2 = System.currentTimeMillis(); for(int i = 0; i < 50000; i++) { variables[i] = new String("hello"); variables[i] = variables[i].intern(); } long endTime2 = System.currentTimeMillis(); System.out.println("Creation time of" + " String objects with intern(): " + (endTime2 - startTime2) + " ms"); } }
Result
The above code sample will produce the following result. The result may vary.
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