Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performance improvement: toString()

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.

like image 744
Diyko Avatar asked Dec 20 '22 09:12

Diyko


2 Answers

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

like image 57
Brian Avatar answered Jan 07 '23 13:01

Brian


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).

like image 28
Fritz Avatar answered Jan 07 '23 11:01

Fritz