The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. The new operator is also followed by a call to a class constructor, which initializes the new object. As string creation is the process optimally working in O(n) time complexity, where n is the length of the string.
Execution time may vary according to the performance of the computational machine.
String str = new String("GeeksforGeeks");
Time required for creation of String using new:
Creation time of String using 'new' keyword : 12 ms
How to Optimize String Creation?
1. By using String.intern() method:
String.intern() Method for storing only one copy of each distinct String Value, which must be immutable. It can be used to return a string from memory if it is created by a new keyword. It creates an exact copy of heap string object in string constant pool.
public String intern()
Return: Interned string.
Time required for creation of String using intern() method:
Creation time of String objects with intern() : 20 ms
The creation time of objects with an intern( ) and creation time of objects with ‘new’ keyword fluctuate near each other’s creation time.
2. By using string literals:
A string literal should be enclosed in double-quotes. Whenever it encounters a string literal in the programmer’s code, the compiler creates a String object with its value.
It is the fastest way of string creation.
String literal = "GeeksforGeeks";
Time required for creation of String using literals:
Creation time of String literals : 9 ms
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.