DEV Community

Discussion on: Performance Benchmarking: String and String Builder

Collapse
 
cicirello profile image
Vincent A. Cicirello • Edited

@kaleemniz I agree with Jean-Michel here. Under-the-hood Java's StringBuilder is implemented as a partially filled array. Doing n appends to a partially filled array requires time that is linear in n. On the other hand, concatenating n equal length strings with + requires time that is quadratic in n since each concat requires filling an increasing length array (length 2 then 3 then 4 .... the sum of which is quadratic in n).

So it is no surprise that with huge n like you are using that the StringBuilder is faster. You don't need to time anything for that. Linear time is asymptotically faster than quadratic time. Big-O however hides the effects of low order terms and constants, etc since it is focused on what happens for large inputs.

Microbenchmarks of alternatives with asymptotically different runtimes is far more interesting for smaller input sizes to discover where the break even point is. If n is 2 for example, concatenating the 2 Strings with + is almost certainly faster than the overhead of creating a StringBuilder, as is likely the case for the next few n as well.

But where is the break even point? When does the StringBuilder actually become faster? Your lowest n is 100000. Which for the task, where you are comparing a linear runtime and a quadratic runtime alternative for the same task, may as well be infinity as it doesn't provide any more info than an asymptotic analysis.

I'd be interested to see what you'll find with small n and using a microbenchmarking framework. When is String concatenating with + faster than using StringBuilder and when does StringBuilder become faster?