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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With