Compare string initialization performance for String Literal and String object.
String str = “GeeksForGeeks”;
This is string literal. When you declare string like this, you are actually calling intern() method on String. This method references internal pool of string objects. If there already exists a string value “GeeksForGeeks”, then str will reference of that string and no new String object will be created. Please refer Initialize and Compare Strings in Java for details.
String str = new String(“GeeksForGeeks”);
This is string object. In this method JVM is forced to create a new string reference, even if “GeeksForGeeks” is in the reference pool.
Therefore, if we compare performance of string literal and string object, string object will always take more time to execute than string literal because it will construct a new string every time it is executed.
Note: Execution time is compiler dependent.
Below is the Java program to compare their performances.
Time taken to execute string literal = 0 Time taken to execute string object = 2
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Object toString() Method in Java
- Java.lang.string.replace() method in Java
- Java.lang.String.matches() in Java
- Java.lang.String.startswith() in Java
- Java.lang.String class in Java | Set 2
- Insert a String into another String in Java
- Convert Set of String to Array of String in Java
- Convert a Set of String to a comma separated String in Java
- Convert a List of String to a comma separated String in Java
- String vs StringBuilder vs StringBuffer in Java
- String to Integer in Java - parseInt()
- Split() String method in Java with examples
- Searching characters and substring in a String in Java
- String class in Java | Set 1
- Reverse a string in Java
- Trim (Remove leading and trailing spaces) a string in Java
- Remove Leading Zeros From String in Java
- Check if a given string is a valid number (Integer or Floating Point) in Java
- Extracting each word from a String using Regex in Java
- Check if a given string is a valid number (Integer or Floating Point) in Java | SET 2 (Regular Expression approach)