Do you understand how it works internally?

Every time you dostringA += stringB;a new string is created an assigned to stringA so it will consume memory (new string instance!) and time (copy the old string + new chars of the other string).

StringBuilderwill use internally an array of chars and when you use.append()method it will do several things:

  • check if there are any free space for the string to append
  • again some internal checks and run a System.arraycopy to copy the chars of the string in the array.

Personally, i think the allocation of a new string every time (creating a new instance of string, put the string etc.) could be very expansive in terms of memory and speed (in while/for etc. especially).

In your example, use aStringBuilderis better but if you need (example) something simple like a.toString()

public String toString()
{
    return StringA + " - " + StringB;
}

makes no differences (well, in this case is better you avoid StringBuilder overhead which is useless here).

https://stackoverflow.com/questions/22439177/why-stringbuilder-is-much-faster-than-string

results matching ""

    No results matching ""