Playing the toStrings

277 views

Published on

Discussing issues when overriding toString() method in java. Three different implementation strategies and general recommendations.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
277
On SlideShare
0
From Embeds
0
Number of Embeds
56
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Playing the toStrings

  1. 1. Java Performance Playing toStrings By Konstantin Pavlov konstantinpavlov.net linkedin.com/in/kpavlov
  2. 2. Object.toString() ❖ Returns string informative representation of an object. ❖ Implementation in class Object returns <class name>@<hashCode> ❖ Is overridden to provide better object view in logs ❖ Application business logic should not relay on a value returned by this method
  3. 3. What can be wrong with toString() method?
  4. 4. There is no problem unless you're getting a High Load!
  5. 5. ❖ Depending on logging strategies, may be called very frequently ❖ This may slow down your system significantly ❖ Creating new object instances (ToStringBuilder) with method is cheap but not free.
  6. 6. Implementation strategies:
  7. 7. Long Living Objects ❖ There are a limited number of long living objects ❖ A set of objects may change at runtime ❖ Used as Map keys ❖ toString is called frequently (logging) ❖ toString is called on the same instance multiple times
  8. 8. Long Living Objects. Solution ❖ Since the instance set is not known at compile time, it is not possible to use Enums. ❖ Use object pool. You'll also be able to use identity equals(==) and identity hashCode. ❖ Evaluate and cache toString value in field of the object ❖ It’s OK to use ToStringBuilder for evaluation ❖ Keep toString value as short as possible
  9. 9. Short Living Objects ❖ e.g. Data Transfer Objects (DTO) ❖ Created frequently ❖ toString usually called once
  10. 10. Short Living Objects. Receipts ❖ Avoid using ToStringBuilder, no need to create extra objects ❖ Use as little fields in toString as possible
  11. 11. Other objects ❖ It is not known yet how frequently object will be used ❖ How long is lifetime?
  12. 12. Other Objects. Solution ❖ Follow KISS principle, keep it simple! ❖ Code must be readable and maintainable!
  13. 13. Final Thoughts
  14. 14. ❖ Don't spend much time on optimization on early phases of the project ❖ But don't put a performance bomb in your code. Try to predict future object usage and don't write a code which will definitely slow your application.
  15. 15. Thanks! konstantinpavlov.net linkedin.com/in/kpavlov

×