Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java logger using ... function [duplicate]

Tags:

java

logging

Java logger allows the following syntax:

m_logger.info("ID: {} NAME: {}", id, name);    // 1
m_logger.info("ID: " + id + " NAME: " + name); // 2

In the first case, essentially we are calling the ... function and thus a new Object[] is created every time.

I ran through YourKit and that's what I see.

My question is that isn't the 1st case an expensive operation that we should be avoiding all the time? But yet I have seen this in a lot of codes. What are we gaining by using #1?

And I suppose we should use StringBuilder for best performance?

like image 573
Theboy Avatar asked Feb 07 '18 11:02

Theboy


2 Answers

m_logger.info("ID: {} NAME: {}", id, name);

It's lazy argument evaluation. If the INFO logging level is turned off, the string won't be processed. Actually, it's not a big deal to construct a new Object[n], n usually (=normally) is < 5.

m_logger.info("ID: " + id + " NAME: " + name);

This string will be constructed every time.

like image 169
Andrew Tobilko Avatar answered Sep 30 '22 09:09

Andrew Tobilko


My question is that isn't the 1st case an expensive operation that we should be avoiding all the time?

No, especially in the grand scheme of a program execution

What are we gaining by using #1?f

Readability, sometimes the first approach is easier to read as code. The resulting log lines are the same

And I suppose we should use StringBuilder for best performance?

No: https://stackoverflow.com/a/1532499/32090

like image 32
Boris Pavlović Avatar answered Sep 30 '22 11:09

Boris Pavlović