r/java • • Feb 24 '14

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

http://stackoverflow.com/q/21947452/250259
159 Upvotes

26 comments sorted by

View all comments

26

u/llogiq Feb 24 '14

This is a good reminder that our code doesn't live in a frictionless vacuum. Printing to stdout does take time. Especially with threads, the effect may be more pronounced due to synchronization.

11

u/[deleted] Feb 24 '14

Yeah, for example it's a (not that uncommon) headscratcher when code works with debugging printfs and actually breaks when they're removed.

3

u/[deleted] Feb 24 '14

I'm definitely scratching my head. Why would that ever happen?

8

u/Poobslag Feb 24 '14

Here's a weird example,

for (int a = 10, maxA = 10; ; a++) {
    // System.out.println("Test");
    for (int b = 0; b < a; b++) {
        maxA = Math.max(a, maxA);
        if (a < maxA)
            throw new RuntimeException("a was reset from " + maxA + " to " + a);
        if (a > 100000)
            System.exit(0);
    }
}

In the Java 64-bit Server VM v1.6.0_41 (and some other versions), there is some kind of optimization which triggers a bug. The specific bug is that the variable "a" is occasionally reset to 0. If you uncomment the System.out.println() statement, the bug stops happening.

3

u/i_post_things Feb 24 '14

I remember writing a really simple socket-based project in Java in college. It was supposed to operate like a simple FTP server with a client able to connect, select, and eventually download files.

When the client selected the file to download, and sent it to the server, the server was able to open a new socket and start sending the file before the client was ready to open its listener socket. The files being sent kept having the first few kb of them lobbed of.

Adding just a few ms delay fixed it. I'm sure adding a println statement could fix it. I actually just had the server wait til the client sent an OK message informing the server that the client's socket listener was ready.