Search code examples
javastringstringbuilder

How many strings are produced in a .toString.split(","); call?


Suppose I have the following code:

StringBuilder sb = new StringBuilder("521,214");
String[] result = sb.toString().split(",");

My question is: does toString().split(",") generate 2 strings or 3 strings? I know that the result String array will have 2 strings - but the toString() call will also generate a string as well - that isn't returned?

Basically, I'm trying to limit the number of strings created for performance purposes and want to know if the toString() call brings the total number of strings created to 3?


Solution

  • There will be five String object created in total by these two lines:

    • "521,214" object passed to StringBuilder's constructor. This object is in the interned pool of strings,
    • "," String object passed to split. This object is also in the interned pool of strings,
    • An equivalent "521,214" object produced by toString. Each call of toString produces a new String object. There is no optimization to see if in identical string object has been requested before.
    • Two String objects for "521" and "214" produced by the split method

    It goes without saying that a String[] array object will be created to hold "521" and "214" objects returned from the split method.