5

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));
Muhammad Hewedy
  • 29,102
  • 44
  • 127
  • 219
  • 4
    The BIG difference you're looking for is *performance*. – Marko Topolnik Apr 27 '14 at 11:49
  • How?And Why not in other parts we see such convention? – Muhammad Hewedy Apr 27 '14 at 11:51
  • You ask *how* is a primitive faster than a wrapper object? In other parts of the JDK they weren't paying as much attention to performance. But when you do a feature whose key benefit is performance, you have another story. – Marko Topolnik Apr 27 '14 at 11:58
  • 2
    There is nothing special about specialisation for primitive types. Take a look at `java.util.Arrays` and you will see, that basically every algorithm exists 8 times. In contrast, _Optional_ only exists four times. – nosid Apr 27 '14 at 12:45
  • 1
    [This answer](http://stackoverflow.com/a/22919112/697630) may add more details to your quest. – Edwin Dalorzo Apr 27 '14 at 20:04

1 Answers1

10

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.

nosid
  • 48,932
  • 13
  • 112
  • 139