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 creationWhen 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.
SyntaxThe 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 OutputCreation 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4