Continued from "Performance difference of using String.intern(), Compare by Reference & Compare by Value - Part 1 / 2", let’s go further on the captioned topic.
How about the cost of applying String.intern()?
Let’s take a look of the following sample code:
public class Test3 {
public void
instantiateNoIntern(){
long start = System.nanoTime();
String a = "ABCDEFGHIJKLMNOPQRSTUV";
String b = new String("ABCDEFGHIJKLMNOPQRSTUV");
long end = System.nanoTime();
System.out.println("Elapsed Time (ns): " + (end - start) );
}
public void
instantiateWithIntern(){
long start = System.nanoTime();
String a = "ABCDEFGHIJKLMNOPQRSTUV";
String b = new String("ABCDEFGHIJKLMNOPQRSTUV").intern();
long end = System.nanoTime();
System.out.println("Elapsed Time (ns): " + (end - start) );
}
public static void main(String[] args){
Test3 test = new Test3();
System.out.println("Instantiation cost NO String.intern() : ");
for (int i = 10; i > 0 ; i--){
test.instantiateNoIntern();
}
System.out.println("");
System.out.println("Instantiation cost with String.intern() : ");
for (int i = 10; i > 0 ; i--){
test.instantiateWithIntern();
}
}
}
|
The execution result is shown below:
Instantiation cost without String.intern() :
Elapsed Time (ns): 3622
Elapsed Time (ns): 603
Elapsed Time (ns): 302
Elapsed Time (ns): 302
Elapsed Time (ns): 302
Elapsed Time (ns): 302
Elapsed Time (ns): 0
Elapsed Time (ns): 302
Elapsed Time (ns): 301
Elapsed Time (ns): 301
Instantiation cost with String.intern() :
Elapsed Time (ns): 2113
Elapsed Time (ns): 604
Elapsed Time (ns): 604
Elapsed Time (ns): 302
Elapsed Time (ns): 905
Elapsed Time (ns): 604
Elapsed Time (ns): 604
Elapsed Time (ns): 604
Elapsed Time (ns): 604
Elapsed Time (ns): 603
|
Total Time (nanosecond)
|
|
Without
applying String.intern()
|
6,337
|
Has
been applying String.intern()
|
7,547
|
Difference
for 100 operations
|
1,210
|
From the result above, we can see that the cost for applying intern() is very low in actual which means intern() is still worth for applying as the time saved by alternatively using Compare by Reference is significant.
Let’s integrate this result with the tables before to get an overall view:
Total Time (nanosecond)
|
Result
Correctness
|
|||
Comparison
operation
|
Instantiation
|
Comparison
Operation + Instantiation
|
||
Before using String.intern()
|
||||
By
Reference
|
2,416
|
6,337
|
8,753
|
Incorrect
|
By Value
|
49,203
|
6,337
|
55,540
|
Correct
|
After using String.intern()
|
||||
By
Reference
|
2,415
|
7,547
|
9,962
|
Correct
|
By Value
|
6,943
|
7,547
|
14,490
|
Correct
|
By Reference: ==
By Value: .equals()
Hope this article is interesting to you and hope you enjoy it!