• Post Reply Bookmark Topic Watch Topic
  • New Topic

String literal and performance  RSS feed

 
R K Singh
Ranch Hand
Posts: 5390
1
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I am assuming that we all familiar with Java String pool.

For quick recap:
The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns.


Now question is, what is better to use, may be for small performance gain, from the following :

Op:1) use a reference variable and point to the string literal and use that variable, instead of string literal

Op:2) dont create a reference variable and use string literal, where ever you want to use.

As per best practice, I should be doing Op:1.
I think that performance wise also Op:1 should be preferred as it will save time for JVM to look up literal pool everytime it finds literal.

But Op:1 also has a overhead of creating a object reference and then pointing it to a reference in literal pool.


Is JVM fast and smart enough to find string from literal pool quickly? (is finding string from pool is heavy weight operation ??)
OR
creating a reference variable is light weight operation?


I hope I was able to explain my doubt.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12559
49
Chrome Java Linux
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As per best practice, you should be writing your code in the cleanest, simplest, and easiest way to read and maintain. Unless you are doing millions of operation, you will never notice any real performance difference. Saving a millionth of a second really doesn't gain you much.

Almost without a doubt, any performance issues you actually have will be elsewhere.
 
R K Singh
Ranch Hand
Posts: 5390
1
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Fred.

Though our application is doing million of transaction, luckily I am not doing any performance improvement right now :-)

It was an hypothetical question, cause sometime smart guys points out such small things in code without having any real data in hand :-|
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66263
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And smart guys say don't worry about premature optimization.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!