Recently I was wondering what the performance difference really is between using a
String literal and using a final static String in a
Java application. I have always heard that using final static String is significantly faster. So I wrote a small program that would measure the time to print a String literal and the time to print a final static String. Here are some of the conditions I used:
- Both strings are the same length (arbitrary 39 characters) but different strings for each.
- I used System.out.println() for each case
- I ran an arbitrary 100 iterations of doing the same println for each in hopes of eliminating any initialization latency.
- Java 1.6 is used
- I used "System.nanoTime()" to get the timings in each case.
To my surprise the String literal printed faster than the final static String in the tests 60 to 70% of the time. In some cases the String literal printed dramatically faster. Now we are talking about timings in the range of between 15000 nanoseconds to 35000 nanoseconds in each
test. However if the application must execute some components at less than one millisecond for instance, this could be influential.
I'd like to know if others have ever run this test and what their findings are.
I am also looking the tests over to see if there are any "gotchas" I might of missed.
Thanks everyone