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 who 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
Pure speculation is that you're using a terminal that attempts to do word-wrapping rather than character-wrapping, and treats
B
as a word character but#
as a non-word character. So when it reaches the end of a line and searches for a place to break the line, it sees a#
almost immediately and happily breaks there; whereas with theB
, it has to keep searching for longer, and may have more text to wrap (which may be expensive on some terminals, e.g., outputting backspaces, then outputting spaces to overwrite the letters being wrapped).But that's pure speculation.
I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8; I used
System.nanoTime()
for measurements.Eclipse:
I got the same time on both cases - around 1.564 seconds.
Netbeans:
So, it looks like Netbeans has bad performance on print to console.
After more research I realized that the problem is line-wrapping of the max buffer of Netbeans (it's not restricted to
System.out.println
command), demonstrated by this code:The time results are less then 1 millisecond every iteration except every fifth iteration, when the time result is around 225 millisecond. Something like (in nanoseconds):
And so on..
Summary: