DEV Community

Discussion on: Performance Benchmarking: String and String Builder

Collapse
 
cicirello profile image
Vincent A. Cicirello • Edited

@kaleemniz there are a couple issues with your comparison. Check out Pavel's comment above on microbenchmarking frameworks. They handle the warmup phase that your comparison overlooks.

Also, the StringBuilder version isn't entirely fair. Ultimately if using a StringBuilder you'll eventually call toString, but yours does not.

I'd also rather see both versions have only n and the appended character as parameters. And instead of void, return a String. And then use a microbenchmarking framework.

Why this suggestion on returning a string and not passing the StringBuilder as a parameter? The version with repeated + is updating parameter variable which is not observable external to the method due to pass by value, and thus even the final string is subject to garbage collection. While in the StringBuilder version, the calls to append are changing state of the StringBuilder you passed, so those changes are externally observable.