0

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()));
7
  • Take a look at the source of String.format to see how it's injecting objects internally. Commented Apr 3, 2013 at 18:53
  • 1
    Are you sure memory is your problem? Have a look at SLF4J not buiding logging strings for unlogged level messages. Commented Apr 3, 2013 at 18:55
  • 2
    For logging, wouldn't you expect the memory used to be immediately garbage collected anyway? Commented Apr 3, 2013 at 19:01
  • @ArneBurmeister Every logging line we have is started with a .isDebugEnabled() for example. Commented Apr 3, 2013 at 19:01
  • Are you just concatenating plain Strings? or is there any formatting/converting envolved? Commented Apr 3, 2013 at 19:04

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.