DEV Community

Discussion on: Optimise your String Algorithms in Java

Collapse
 
cicirello profile image
Vincent A. Cicirello

Your time and space complexity for concatenation is not correct. For concatenating 2 strings of lengths n and m, it is just O(n + m). Your example of what happens during a concatenation is not correct. Concatenating "abc" + "def" is not implemented as 3 separate concats. That would be terribly inefficient. During a single concat, both lengths are known. A new string of length n+m is allocated and the characters of each copied into it.

Using a StringBuilder to concat 2 strings is likewise O(n + m). The behavior is a bit different though. StringBuilder is implemented as a partially-filled array. The purpose is to speed things up if you are doing many concats. But for doing a single concat of 2 strings of lengths n and m, the time complexity of both the concat operator + as well as using a StringBuilder is the same, although for that simple case the StringBuilder will be slightly slower due to some overhead.

A StringBuilder is only faster if you need to combine many strings. The amortized runtime of concatenating X strings with a StringBuilder is O(sum of the lengths of all the strings). The partially filled array approach doubles the size of the buffer whenever it is full to achieve this amortized runtime.

Using + repeatedly instead would be worse than that because every concat with + requires allocating a new string. The specific runtime depends on number of concats and lengths of strings. For simple example, concatenating n strings of length 1 with n-1 concats will run in O(n^2), whereas calling append on a StringBuilder n times to do the same will be O(n).

But the basic case of 1 concat of 2 strings lengths n and m, both + and StringBuilder are O(n+m) with StringBuilder having higher constant factors that O() hides.