what's log4j actually doing when we turn on or off some log places?

后端 未结 3 1836
礼貌的吻别
礼貌的吻别 2021-01-04 18:02

We know we can config log4j to turn off log on specific places (class or package in Java) via its properties/configuration file. My questions are followed:

  1. wha
3条回答
  •  太阳男子
    2021-01-04 19:00

    I ran a simple benchmark to test.

        for (int j = 0; j < 5; j++) {
            long t1 = System.nanoTime() / 1000000;
            int iterations = 1000000;
            for (int i = 0; i < iterations; i++) {
                int test = i % 10;
                log.debug("Test " + i + " has value " + test);
            }
            long t2 = System.nanoTime() / 1000000;
            log.info("elapsed time: " + (t2 - t1));
    
            long t3 = System.nanoTime() / 1000000;
            for (int i = 0; i < iterations; i++) {
                int test = i % 10;
                if (log.isDebugEnabled()) {
                    log.debug("Test " + i + " has value " + test);
                }
            }
            long t4 = System.nanoTime() / 1000000;
            log.info("elapsed time 2: " + (t4 - t3));
        }
    
    elapsed time: 539
    elapsed time 2: 17
    elapsed time: 450
    elapsed time 2: 18
    elapsed time: 454
    elapsed time 2: 19
    elapsed time: 454
    elapsed time 2: 17
    elapsed time: 450
    elapsed time 2: 19
    

    With 1.6.0_18, which surprised me as I would have thought the inlining would have prevented this. Maybe Java 7 with escape analysis will.

    However I still wouldn't wrap debug statements in an if clause unless time improvements of the order of half a microsecond get to be important!

提交回复
热议问题