Intro
This is a follow-up to an earlier post where I was speculating that Java's Just In Time compilation may have been causing significant performance differences when some code was being exercised more than one or two times.Here is a snippet of the code which I would like to focus on:
int anIndex = Collections.binarySearch(sorted, target,
(o1, o2) -> o1.compareTo(o2) );
The title of this post should have given away that the lambda expression made the performance take a hit until something kicked in and probably replace the lambda setup in each loop iteration with a single instance.
Alternatives
ComparatorintComparator = Integer::compareTo;
int anIndex = Collections.binarySearch(sorted, target, intComparator);
Also uses some Java 8 magic and performs slowly.
ComparatorintComparator = new Comparator () { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } };int anIndex = Collections.binarySearch(sorted, target, intComparator);
Doesn't use any lambda expressions and performs quickly.
The final, slightly embarrassing example:
int anIndex = Collections.binarySearch(sorted, target);
So, I didn't even need to define the method for the comparison.
No comments:
Post a Comment