devxlogo

Performance Measurements with String Class Usage

Performance Measurements with String Class Usage

The new keyword definitely consumes more time when compared to direct initializing the value to a String object.

The following illustrates the time consumed by both the mechanisms. These values may vary from environment to environment. Code snippet:

public class StringCreationAndPerformance{   public static void main(String args[])   {      StringCreationAndPerformance stringCreationAndPerformance = new StringCreationAndPerformance();      stringCreationAndPerformance.proceed();   }      private void proceed()   {      long startTime = 0, endTime = 0;      int numberOfObjects = 10000000;      startTime = System.currentTimeMillis();      System.out.println("Start time: With new operator: " + startTime);      for (int i=0;i        {         String newString = new String("With new");      }      endTime = System.currentTimeMillis();      System.out.println("End time: With new operator: " + endTime);      System.out.println("Total time: With new operator: " + (endTime-startTime));      startTime = System.currentTimeMillis();      System.out.println("Start time: With = operator: " + startTime);      for (int i=0;i        {         String newString = "Without";      }      endTime = System.currentTimeMillis();      System.out.println("End time: With = operator: " + endTime);      System.out.println("Total time: With = operator: " + (endTime-startTime));         }}/*

Expected output:

[root@mypc]# java StringCreationAndPerformanceStart time: With new operator: 1506426921408End time: With new operator: 1506426921439Total time: With new operator: 31Start time: With = operator: 1506426921440End time: With = operator: 1506426921443Total time: With = operator: 3*/
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist