Tranquility
Tranquility

Reputation: 3291

Performance of thenComparing vs thenComparingInt - which to use?

I have a question, if I'm comparing ints, is there a performance difference in calling thenComparingInt(My::intMethod) vs thenComparing(My::intMethod), in other words, if I'm comparing differemt types, both reference and primitive, e.g. String, int, etc. Part of me just wants to say comparing().thenComparing().thenComparing() etc, but should I do comparing.thenComparing().thenComparingInt() if the 3rd call was comparing an int or Integer value?

I am assuming that comparing() and thenComparing() use the compareTo method to compare any given type behind the scenes or possibly for ints, the Integer.compare? I'm also assuming the answer to my original question may involve performance in that thenComparingInt would know an int is being passed in, whereas, thenComparing would have to autobox int to Integer then maybe cast to Object?

Also, another question whilst I think of it - is there a way of chaining method references, e.g. Song::getArtist::length where getArtist returns a string? Reason is I wanted to do something like this:

songlist.sort(
            Comparator.comparing((Song s) -> s.getArtist().length()));


    songlist.sort(
            Comparator.comparing(Song::getArtist, 
                    Comparator.comparingInt(String::length)));


    songlist.sort(
            Comparator.comparing(Song::getArtist, String::length));

Of the 3 examples, the top two compile but the bottom seems to throw a compilation error in Eclipse, I would have thought the 2nd argument of String::length was valid? But maybe not as it's expecting a Comparator not a function?

Upvotes: 4

Views: 3832

Answers (1)

dkatzel
dkatzel

Reputation: 31648

Question 1

I would think thenComparingInt(My::intMethod) might be better since it should avoid boxing, but you would have to try out both versions to see if it really makes a difference.

Question 2

songlist.sort(
        Comparator.comparing(Song::getArtist, String::length));

Is invalid because the 2nd parameter should be a Comparator not a method that returns int.

Upvotes: 4

Related Questions