On page 140 of Effective Java we are advised that a method signature with a wildcard is preferable to one with a type parameter that only appears once. For example,
public static void swap(List<?> list, int i, int j)
is preferable to
public static <T> void swap(List<T> list, int i, int j)
However it is not possible to set an item of a List<?>
to be anything (except null
) so Effective Java suggests writing a private helper method to make the signature with a wildcard work.
private static <T> void swapHelper(List<T> list, int i, int j) {
list.set(i, list.set(j, list.get(i)));
}
public static void swap(List<?> list, int i, int j) {
swapHelper(list, i, j);
}
However I looked at the source code for Collections.swap
and discovered that the way that they got around the List<?>
problem was to use raw types.
public static void swap(List<?> list, int i, int j) {
final List l = list;
l.set(i, l.set(j, l.get(i)));
}
We are advised not to use raw types in new code (except in instanceof
checks). So, I would like to know what is the reason here? Is there a performance benefit in using raw types here rather than calling a private helper method? If not, are there any examples where using raw types can improve performance?
Premature optimization is the root of all evil. You will most likely find it to be the case that the JIT compiler inlines both your swap method and your swapHelper method if they turn out to be performance bottlenecks. In general, the Java JIT compiler is very good in detecting performance bottlenecks.
However, if you're interested about performance then why not write a benchmark for both the Collections.swap method and your variant which uses a helper method. That would provide you with an answer to this question. Just be sure to do enough many iterations that the JIT compiler recognises the swap functions as bottlenecks and optimizes the bottlenecks away by inlining the method calls.
I would follow the advice given by Effective Java instead of the code in Collections.swap. I think you just found evidence that programmers take shortcuts sometimes. It doesn't mean you should be doing the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With