We are developing quite big server app. Each action is tracked by log. There are many logs with calling of toString method. Unfortunatelly we need most of them on other hand we cannot track what happens on prod. Is it make sense trying to improve toString method? Forexample put result of toString in memory and update if some field was updated.
example of my toString
public classs InMessage{
//declared 20+ fields
@Override
public String toString() {
StringBuilder builder = new StringBuilder(this.getClass().getSimpleName());
builder.append(": [");
builder.append(super.toString());
builder.append("; updateTime: ");
builder.append(updateTime);
//forexample 20 fields here
builder.append(";]");
return builder.toString();
}}
then we process InMessage in some way and log each action
log.debug("We received inMessage: {}", inMessage);
after this discussion we decided to decrease number of logs where it's possible and nothing more.
Unless you are actively experiencing performance or memory issues, don't worry about it. Useful logs can help enormously in prod diagnostics, you need to weigh that against hypothetical performance worries that might just never happen.
(Not saying you're definitely going to be problem-free here, just don't optimise for something that's not really a problem...)
Edit: trust your own judgement on whether you're logging "too much"; if a single UI or service operation generates 20 pages of incidental / debug level information, even at INFO level logging, you might want to refine the content to make it genuinely useful
That nano-optimization usually ends up in useless effort that add no overall value with the exception of some ms substracted from a time handled in seconds or, sometimes, minutes. Depends on the case but yours could be one of those where every little bit counts.
Identify an optimization need based on data, don't pre-optimize and in particular with such methods. I bet there are other approaches that could prove more valuable than questioning the use of toString
like, for example, improving the order of a commonly used algorith or reducing the load of an operation (less calls, but significant ones).
Just compare the usage of toString
with the solution you have in mind, you're implementing a kind of observer pattern that updates a central string repository if a field is changed? That's executing code on every setter (if you use that approach).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With