I have so many use cases where I have to initialize a large string and not use the same string anywhere else.

//Code-1
public class Engine{
public void run(){
    String q = "fjfjljkljflajlfjalkjdfkljaflkjdllllllllllllllsjfkjdaljdfkdjfnvnvnrrukvnfknv";
    //do something
   }
}

I call this run method very few times.

In Code-1 the string fjfjljkljflaj..... will get added to the string pool and will never get collected by GC. So I am thinking to initialize with the new operator.

//Code-2
public class Engine{
public void run(){
    String q = new String("fjfjljkljflajlfjalkjdfkljaflkjdllllllllllllllsjfkjdaljdfkdjfnvnvnrru");
    //do something
   }
}

Will 2nd code save some memory or there will be other factors to consider to decide which one is efficient?

1

There are 1 best solutions below

0
On

first thing -- if we create with the new String() object, the constant won't be created in the literal pool unless we call the intern() method.

In terms of optimization, we should use the String literal notation when possible. It is easier to read and it gives the compiler a chance to optimize our code.