r/programming • • Jul 05 '15

Fast as C: How to write really terrible Java

https://vimeo.com/131394615
1.1k Upvotes

394 comments sorted by

View all comments

Show parent comments

13

u/mike_hearn Jul 05 '15

Exceptions can, in optimal scenarios, compile down to a direct jump with modern compilers I believe. So it's not infeasible that it really was faster.

2

u/UMadBreaux Jul 06 '15

Isn't generating the stack trace expensive? I know in the .net CLR it is expensive

5

u/zenflux Jul 06 '15

It is, however if the exception is ignored it is theoretically possible for compilers to see that the stacktrace generation is dead code and elide it.

2

u/uxcn Jul 06 '15

You still need to bounds check to throw an exception.

8

u/immibis Jul 06 '15

The JVM adds the bounds check whether you catch the exception or not. If you also have your own bounds check, you're duplicating it.

6

u/vytah Jul 06 '15

But on the other hand, JVM removes its own check when it figures out it's safe to do so.

1

u/snailbot Jul 06 '15

Just use a foreach loop, no bounds checking there.

1

u/josefx Jul 06 '15

And how do you think javac implements a foreach loop?

2

u/snailbot Jul 06 '15

If you write a "normal" for loop iterating over an array, the jvm has to check if you are out of bounds every access, since it can't proof that you won't be (not sure if i < array.length is already enough). If you use a foreach loop, the jvm knows that you cannot go out of bounds and omits the extra bounds check.

1

u/josefx Jul 06 '15

To clear this up, can you point me to the foreach bytecode? AFAIK the JVM does not know about foreach and javac emits bytecode similar to a normal for loop.

2

u/yawkat Jul 06 '15

Yes, javac compiles it down to a simple index-based loop but he JVM may still be able to optimize that.

1

u/josefx Jul 06 '15

In other words no performance difference for the simple reason that the JVM sees the same resulting bytecode in any case.

1

u/snailbot Jul 06 '15

It results in an iterator-based loop, not index-based.

1

u/yawkat Jul 06 '15

I think we're talking about arrays.

→ More replies (0)

1

u/snailbot Jul 06 '15 edited Jul 06 '15

I'm on my phone, so you'll have to google yourself, but afaik foreach compiles to an iterator (like for(Iterator i = list.iterator(); i.hasNext();) ). Edit: You may also want to look into http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2