문제

I noticed that, There are multiple versions of many Types in Java 8.

For example, The introduced Optional class has many flavors of OptionalInt, OptionalLong etc..

Although the Optional has a type Parameter (Optional<T>), we still need some specific types for primitives, Why?

I cannot find a BIG difference between the following:

Optional<Integer> o = Arrays.asList(1, 3, 6, 5).stream().filter(i -> i % 2 == 0).findAny();
System.out.println(o.orElse(-1));

OptionalInt oi = Arrays.stream(new int[] { 1, 3, 6, 5 }).filter(i -> i % 2 == 0).findAny();
System.out.println(oi.orElse(-1));
도움이 되었습니까?

해결책

It's true that Optional<Integer> behaves quite similar to OptionalInt from a functional point of view. For example, there is no functional difference between the following to methods:

int foo(int value) {
    return OptionalInt.of(value).orElse(4242);
}
int bar(int value) {
    return Optional.of(value).orElse(4242);
}

However, there can be a difference in performance and efficiency--depending on how the optional types are used and on the capabilities of the JIT compiler. The second method is basically identical to the following method:

int baz(int value) {
    return Optional.of(Integer.valueOf(value))
        .orElse(Integer.valueOf(4242))
        .intValue();
}

As you can see, due to auto-boxing for each method call up to two additional Integer objects will be created. Compared to native types, the creation of an object is expensive, and each additional object increases the pressure on the garbage collection.

That doesn't mean, that it will make a difference for most applications. But it can make a difference, and if it's not there, it lowers the acceptance for Java 8 Streams.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top