How can we compare String creation performance?

In this article we will discuss performance wise what is the best way to create String object.

There are two ways to create String object:

  1. By string literal

String str = “10Article”;

When we create string literal then JVM checks Heap string constant pool first. If the string already exists in the pool, a reference to the pooled instance is return. If string doesn’t exist in the pool, a new string instance is created.

2. By new keyword

String str = new String(“10Article “);

New Object will create in Heap Memory.

By following program we can compare both way performance.

 

 Source Code:
 package com;

public class Test {

	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();

		for (int element = 0; element < 9000; element++) {
			String str1 = "10Article";
			String str2 = "10Article";
		}
		long endTime = System.currentTimeMillis();
		System.out
				.println("Total time to create 100 String literal in milli seconds : "
						+ (endTime - startTime));
		long startTime1 = System.currentTimeMillis();

		for (int element = 0; element < 9000; element++) {
			String str3 = new String("10Article");
			String str4 = new String("10Article");
		}
		long endTime1 = System.currentTimeMillis();
		System.out
				.println("Total time to create 100 String object by new keyword : "
						+ (endTime1 - startTime1));

	}

}
Output:

Total time to create 100 String literal in milli seconds : 0
Total time to create 100 String object by new keyword : 8



10article.com Tutorials

10article.com Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *