0

slf4j's advantage is that it avoids overhead of string concatenation, by providing {}. Why can't this be done with existing System.out.println() method by overloading it?

Community
  • 1
  • 1
a3.14_Infinity
  • 5,653
  • 7
  • 42
  • 66

1 Answers1

1

The performance advantage you mention exists only when the message that would be created is actually ignored afterwards and the message is discarded without being used. Whenever the string will actually be used (e.g., logged or printed), there is no performance advantage of using format strings.

Thus this advantage only exists for logging methods, when the level of the log message is lower than the current log level set in the logger. In this situation, the string concatenation can be avoided completely if using format strings and passing the arguments separately. This is a common case, because most of the log messages typically have a low level, and most of the time the actual log level is set to something higher. So in production, where performance is important, most of the log messages can be ignored and need not have their full string created.

For System.out.println(), this advantage does not exist, because standard out is always active. Every call to it will lead to the string for the message being created and printed. There is no log level for System.out.println() which could be set to a higher value to ignore some of the calls to this message. Thus the string concatenation always has to be done, and it is irrelevant whether it is done by the calling code, or by the method itself.

Furthermore, as Oliver mentioned, a similar method exists with System.out.printf(), only the syntax of the format string is different.

Philipp Wendler
  • 11,184
  • 7
  • 52
  • 87