Raw Types and Performance

On page 140 of Effective Java, we recommend that the method signature with a wildcard is preferable to one with a type parameter that appears only once. For instance,

public static void swap(List<?> list, int i, int j) 

preferable

 public static <T> void swap(List<T> list, int i, int j) 

However, it is not possible to set the List<?> Element in any way (other than null ), so effective Java suggests writing a private helper method to make a wildcard signature.

 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 found that the way they encountered 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 not encouraged to use raw types in new code (except for instanceof checks). So, I would like to know what is the reason? Is there a performance advantage when using the source types here, rather than calling a private helper method? If not, are there examples where using raw types can improve performance?

+5
source share
1 answer

Premature optimization is the root of all evil. You will most likely find that the JIT compiler includes both your swap method and your swapHelper method if they turn out to be performance bottlenecks. In general, the Java JIT compiler is very well versed in performance bottlenecks.

However, if you are interested in performance, then why not write a control value for the Collections.swap method and your option, which uses a helper method. This will give you the answer to this question. Just remember to do enough iterations so that the JIT compiler recognizes swap functions as bottlenecks and optimizes bottlenecks by nesting method calls.

I would take advantage of the recommendation provided by Effective Java instead of the code in Collections.swap. I think you just found evidence that programmers sometimes use shortcuts. This does not mean that you should do the same.

+6
source

Source: https://habr.com/ru/post/1215752/


All Articles