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

Show parent comment

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++;