小能豆

Why is printing "B" dramatically slower than printing "#"?

javascript

I generated two matrices of 1000 x 1000:

First Matrix: O and #.
Second Matrix: O and B.

Using the following code, the first matrix took 8.52 seconds to complete:

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("");
 }

With this code, the second matrix took 259.152 seconds to complete:

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"); // only line changed
        }
    }

    System.out.println("");
}

What is the reason behind the dramatically different run times?


As suggested in the comments, printing only System.out.print("#"); takes 7.8871 seconds, whereas System.out.print("B"); gives still printing....

As others pointed out that it works for them normally, I tried Ideone.com for instance, and both pieces of code execute at the same speed.

Test Conditions:

  • I ran this test from Netbeans 7.2, with the output into its console
  • I used System.nanoTime() for measurements

阅读 84

收藏
2023-12-25

共1个答案

小能豆

The significant difference in runtime you’re observing might be related to the way console output is handled in your specific development environment (NetBeans in this case).

Printing to the console can be a relatively slow operation, especially if the console has to update the display for each character printed. When you switch from printing "#" to printing "B", it might be triggering some additional processing or rendering that is causing the slowdown.

It’s worth noting that the actual computational work in both cases is quite similar, and the time difference is likely due to how the console output is being handled by the development environment.

To get a more accurate measure of the actual computational time, you might want to consider measuring the time it takes to generate the matrices without printing them to the console. Instead, you could store the generated characters in memory (e.g., in a 2D array), and then measure the time separately for the printing operation. This will help you isolate whether the slowdown is due to the generation of the data or the console output.

2023-12-25