Hacker News new | ask | show | jobs
by kpw94 87 days ago
The Autoboxing example imo is a case of "Java isn't so fast". Why can't this be optimized behind the scenes by the compiler ?

Rest of advice is great: things compilers can't really catch but a good code reviewer should point out.

2 comments

javac for better or worse is aggressively against doing optimizations to the point of producing the most ridiculously bad code. The belief tends to be that the JIT will do a better job fixing it if it has byte code that's as close as possible to the original code. But this only helps if a) the code ever gets JIT'd at all (rarely true for eg class initializers), and b) the JIT has the budget to do that optimization. Although JITs have the advantage of runtime information, they are also under immense pressure to produce any optimizations as fast as possible. So they rarely do the level of deep optimizations of an offline compiler.
Why should compiler optimize obviously dumb code? If developer wants to create billions of heap objects, compiler should respect him. Optimizing dumb code is what made C++ unbearable. When you write one code and compilers generates completely different code.
The problem is rather that Java doesn't have generics and structs, so you're kind of forced to box things or can't use collections.
No, in the example they provided, programmer wrote obviously stupid code. It has nothing to do with necessity:

    Long sum = 0L;
    for (Long value : values) {
        sum += value;
    }
I also want to highlight that there are plenty of collections utilizing primitive types. They're not generic but they do the job, so if you have a bottleneck, you can solve it.

That said, TBH I think that adding autoboxing to the language was an error. It makes bad code look too innocent. Without autoboxing, this code would look like a mess and probably would have been caught earlier.

>They're not generic but they do the job, so if you have a bottleneck, you can solve it.

But that's the thing, in other languages you don't need a workaround to work on primitives directly.