loops - java - try/catch finally is finally always executed - 为什么打印 "B "比打印 "#"要慢得多?

java loop performance optimization / java / performance / for-loop / system.out

我生成了两个 1000 x 1000 的矩阵:

使用以下代码,第一个矩阵需要8.52秒才能完成。

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
            System.out.print("O");
        } else {
            System.out.print("#");
        }
    }

   System.out.println("");
 }

用这个代码,第二个矩阵需要259.152秒才能完成。

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
            System.out.print("O");
        } else {
            System.out.print("B"); //仅更改一行
        }
    }

    System.out.println("");
}

cнŝdk



Answer #1
for (int i = 0; i < 1000; i++) {
    long t1 = System.nanoTime();
    System.out.print("BBB......BBB"); \\<-contain 1000 "B"
    long t2 = System.nanoTime();
    System.out.println(t2-t1);
    System.out.println("");
}

除时间间隔大约为225毫秒外,每次迭代的时间结果小于1毫秒(每五次迭代除外)。大约(以纳秒为单位):

BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.