Java logger using ... function

Java logger allows you to use the following syntax:

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

In the first case, in fact, we call the function ..., and each time a new one is created Object[].

I ran through YourKit and this is what I see.

My question is, is this not the first case of an expensive operation that we must avoid all the time? But still I have seen this in many codes. What do we get using # 1?

And I suggest that for best performance we should use StringBuilder?

+6
source share
5 answers
m_logger.info("ID: {} NAME: {}", id, name);

. INFO , . , new Object[n], n (= ) < 5.

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

.

+5

, , ?

,

, # 1? f

, .

, StringBuilder?

: fooobar.com/questions/4042/...

+2

Object[] # 1. , StringBuilder, # 2 * toString() id, name (, , String , ).

m_logger.info # 1, , .

, , Object[] , . , , Object[] , # 1.

* StringBuilder, . . Q & A , Java .

+2

.

  • .

    (.. ), (, ERROR). , , , . , StringBuilder , .

  • Flow execution. View the source code of the logger (log4j 2.7)

    @Override
    public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message,
        final Object p0, final Object p1) {
        if (isEnabled(level, marker, message, p0, p1)) {
          logMessage(fqcn, level, marker, message, p0, p1);
      }
    }
    

    He verifies in the sentence ifthat the corresponding mode is enabled. As soon as Java will evaluate this thread, as soon as it becomes faster using optimization branch prediction.

+2
source

This is for users according to my knowledge.

  • Some developers may practice Case No. 1.
  • Some developers may practice Case No. 2.

And this is the main characteristic of Java. The same thing in many ways.

0
source

All Articles