简体   繁体   中英

Which uses less memory String.format or +/StringBuilder?

I've been searching through SO for awhile and all I can find is references to speed for strings and one or two rather misguided attempts at memory benchmarking.

My situation is that we have a ton of logging messages in our application and we're wondering if there is any measurable MEMORY advantage to using String.format vs. + vs. StringBuilder.

I've got a solid grip on measuring the time each of these is taking and there are plenty of SO posts for that.

Can anyone tell me which one is better for lowering memory consumption?

Example:

if(LOG.isDebugEnabled()) LOG.debug(String.format("Invoice id = %s is waiting for processing", invoice.getId()));

Since String.format() is much more complicated because it supports format sequences and data types (%s, %d etc) it is expected to be more performance and memory expensive. However I believe this may be significant for very long strings only.

I believe String.format would use less memory. When using StringBuilder, you need to create a new builder object and then append string to it. The creation of the object and the constant references to it (via append or similar methods) would seem to me to be more memory intensive than to return a straight forward string using String.format.

StringBuilder uses a temporary object before creating the final string. String.format seems like a more direct way and therefore less memory intensive. Moreover, StringBuilder asks for a specific size when initialized (or else it will default to some value). You could compare the default allocated memory values of a StringBuilder object versus a plain old String object.

You could test these two options with a large dataset of strings to be built and assessing the time it takes for each approach.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM