简体   繁体   中英

Does java compiler convert Function<Double,Integer> to DoubleToIntFunction?

Function<Double,Integer> f1=(d)-> {
        if(d>5)
            return 0;
        return 1;
    };
DoubleToIntFunction f2=(d)-> {
        if(d>5)
            return 1;
        return 0;
    };
double d=5.0;
f1.apply(d);
f2.applyAsInt(d);

Will f1 be optimized into DoubleToIntFunction(someting like f2).

I don't see how it could, the upper lambda allows nulls while the lower one doesn't. The compiler would have to do a ton of static code analysis to see if a null could ever be passed to the Function in order to optimize it.

f1.apply(null); //works!
f2.applyAsInt(null); //won't compile!

Assuming two things, this might happen in the future as far as I can tell. 1) Double and Integer could be value types ; thus never null and 2) an AOT javac compiler would be in place.

Not sure if that is feasible still.. That would add a lot of time to the javac total compilation time due to the total number of possibilities and places where optimizations like this could happen.

The Java compiler (javac) does not perform such kind of optimizations. In fact, as indicated in Optimization by Java Compiler , it only performs little optimizations in order to let all available information to the JIT compiler.

So if you declare some lambda as Function<Double,Integer> , the bytecode will represent it as such – well, with its raw type, Function .

Now, depending on the context and execution load of that portion of code, the JIT compiler might be able to inline the lambda (or other implementation of that Function ) and produce very similar or even identical machine code to what it would produce with the DoubleToIntFunction version.

Note that in that case, the type information disappears entirely. It does not replace one with another.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM