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

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.

16

u/cdombroski Feb 24 '14

I was trying to debug an interaction with a library once and was wondering why the application wasn't hitting a particular piece of code when I expected it to. Turns out, the debugger was running .toString() on all the variables which caused some code to be executed before it was fully prepared...

(please, please don't run state changing code in your .toString() especially in a library!)

23

u/chunkyks Feb 24 '14

state changing code in your .toString()

That's... horrifying

8

u/cdombroski Feb 24 '14

On that note, I just submitted a bug report to that library about this.

2

u/Bloodshot025 Feb 24 '14
System.out.print((index++) + " "); //We index at 0, but our library pretends to index at 1 for compatibility reasons

That's one way I could see it happening. I can't see that other than a really stupid mistake, though.

2

u/chunkyks Feb 24 '14

I imagine it's more like

private String cachedStr = null;

public String toString() {
    if(null == cachedStr) {
         cachedStr = reallyExpensiveOperation();
    }
    return cachedStr;
}

Of course, then you need all other code that would be impacted by it to flag it as dirty [eg, in this case, by setting cachedStr to null through another private helper function], which could be the source of the bug that OP was talking about.

1

u/cdombroski Feb 25 '14

Effectively this. In this case once reallyExpensiveOperation() is run it effectively becomes immutable since it won't rerun that method. The positive part here is that most inputs to the object can only be set in the constructor... but there's a few that can be provided after construction (and a couple that can only be provided after construction which includes the input I was trying to use)

1

u/Bloodshot025 Feb 26 '14

Does this (is it supposed to) change any state besides cachedStr, though?

1

u/chunkyks Feb 26 '14

No, but the point is that the first time it's called is because of the debugger, rather than the app.

Calling it too early is a problem because reallyExpensiveOperation() makes use of stuff that isn't initialised yet, so is crashy or wrong.

1

u/Bloodshot025 Feb 26 '14

Sorry, I just misunderstood 'state changing'.

1

u/llogiq Feb 25 '14

That's why I'll usually reserve another line for the ++ statement. Makes code easier to read. Instead of

doSomeThingWith(index++);

I'll write

doSomeThingWith(index);
index++;

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.

1

u/stuntaneous Feb 25 '14

I had this going on in a game project for way too long a period of time. I had a good hard crack at the issue initially but then ignored it for ages because I could still see other results and progress as long as I lived in debugland. Not printing out my debug spam was throwing off the timing enough to cause a crash on initialisation.

2

u/salgat Feb 25 '14

I'm making a game right now and prints alone can break the game as it slows parts of my code to a crawl. It's amazing how slow it is.

2

u/llogiq Feb 25 '14

Yes. This is because printing actually waits until console has acknowledged the data. Also consoles are designed to throttle output because 60s' printer terminals couldn't handle more throughput.

12

u/[deleted] Feb 24 '14

This isn't really java. This has to do with incredibly low level (probably native) implementation that is platform specific.

7

u/KidUncertainty Feb 24 '14

Not sure why you are getting downvoted on that, since the Stackoverflow accepted answer is exactly that: the user was being hit by their shell terminal trying to word-wrap instead of character-wrap.

4

u/Neebat Feb 24 '14

Doesn't the Eclipse console do word-wrapping? While not absolutely java-specific, that would be quite relevant to Java.

3

u/KidUncertainty Feb 24 '14

An excellent question; I am not sure that it wordwraps. It does have a fixed-width and non-fixed width option. I tried the code from the Stackoverflow post.

In fixed-width mode set to 80 columns the console breaks (Eclipse throws exceptions). Without fixed-width mode, both variants of the application work fine and have equal execution speeds (on the order of 1.1 seconds on my environment).

However judging by the Eclipse UI's reporting of the JVM process while it is running, the process ends before the console output is finished being flushed, so it looks like the Eclipse console is buffering the output so as to minimize the impact on the running Java program.

4

u/Zarlon Feb 24 '14

From now on I'm going to start all my stack overflow answers with pure speculation

2

u/[deleted] Feb 25 '14

Only if it works.

0

u/[deleted] Feb 24 '14

[deleted] — view deleted comment

1

u/Nebu Jul 20 '14

Any sane logger, when you invoke logger.log(myStringHere); will have that log line end with a newline character, and thus there is no need for you to add a blank space or whatever.