Search code examples
javaperformancetostring

Is java's toString() evaluated if you don't call it in your code?


If you never explicitly or implicitly call a toString() method in your java code is there a chance it might still be evaluated by some JVM internals (or frameworks)?

The reason for asking is to understand if doing extra work in the toString() method of a class might have any performance impact.

The underlying use case for having the toString() is to make debugging and logging more comfortable, i.e. the method is only used with DEBUG logging level for diagnostic purposes but not in regular production mode.


Solution

  • Not likely but given you state "JVM Internals" or "Frameworks" and not exactly which JVM implementations or what framework, it's hard to give guarantees.

    A way is to find out if you have any implicit or under the hood calls by doing something nasty in the toString, like crashing, exception, logg, exit or Thread.sleep(10000) and make a test run to see if your application hits the toString. If not, there should be no performance implications since even if there is an odd case of something calling toString, it shouldn't be in the hot path.