Search code examples
javastringstringbuffer

What will use more memory


I am working on improving the performance of my app. I am confused about which of the following will use more memory: Here sb is StringBuffer

String strWithLink = sb.toString();
clickHereTextview.setText(
     Html.fromHtml(strWithLink.substring(0,strWithLink.indexOf("+"))));

OR

clickHereTextview.setText(
     Html.fromHtml(sb.toString().substring(0,sb.toString().indexOf("+"))));

Solution

  • In terms of memory an expression such as

    sb.toString().indexOf("+")
    

    has little to no impact as the string will be garbage collected right after evaluation. (To avoid even the temporary memory usage, I would recommend doing

    sb.indexOf("+")
    

    instead though.)

    However, there's a potential leak involved when you use String.substring. Last time I checked the the substring basically returns a view of the original string, so the original string is still resident in memory.

    The workaround is to do

    String strWithLink = sb.toString();
    ... new String(strWithLink.substring(0,strWithLink.indexOf("+"))) ...
        ^^^^^^^^^^
    

    to detach the wanted string, from the original (potentially large) string. Same applies for String.split as discussed over here: