Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Performance Measurements with String Class Usage

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


advertisement

WEBINAR: On-Demand

Unleash Your DevOps Strategy by Synchronizing Application and Database Changes REGISTER >

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 StringCreationAndPerformance
Start time: With new operator: 1506426921408
End time: With new operator: 1506426921439
Total time: With new operator: 31
Start time: With = operator: 1506426921440
End time: With = operator: 1506426921443
Total time: With = operator: 3

*/

 

Visit the DevX Tip Bank

 





   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date