Friday, May 21, 2010

Java String manipulation: Appending empty string to 'var.subString(x,y)' saves memory...


In java usually we do SubString operation as follows.


    String strMainData = "Some long String..." ;
    String strSub= strMainData.subString(i,j); // Where i and j are index values...

This operation will keep the reference to same object strMainData,but only returns smaller string as per the indexes. So it uses same memory as the original String.

We should use it as follows.

    String strSub = new String(strMainData.subString(i,j));
OR

    String strSub = strMainData.subString(i,j) +"";
This will only keep the reference to new smaller String and removes reference to original String variable.



0 Comments: