views:

465

answers:

4

I profiled my code and found out that my class, which implements Comparable<T>, spends 8x more cpu time in

compareTo(Object)

than in

compareTo(T)

I assume that the slowdown is because of virtual table lookup for this method.


Is there a way to force static invocation of the function? (like in non virtual C++ methods)

I still want to use the Comparable<T> interface since I use TreeSet with this object and I'd like not to rewrite this code.


EDIT: No, I didn't implement the compareTo(Object) - this was automatically generated and reported by the profiler

+1  A: 

Since java does not preserve generic types at runtime, ideally both of them should behave the same. Probably, there is something else which is causing the problem.

+4  A: 

the reason you are seeing compareTo(Object) is because of Type Erasure. it just means that at runtime the type information is no longer needed for comparing the values. most likely the reason for your slowdown is 1) very, very big TreeSet with lots of elements 2) - more likely - your compareTo method does something expensive. because it is called very often (n*ln(n) times typically ), it should be implemented efficiently

Andreas Petersson
I do use a large TreeSet intentionally, and that's why I tried to make it as fast as possible - it has one dereferencing and two comparisons only.
Dani
use treeSet only when neccesary. if you need your set sorted only at certain times, consiser using HashSet and sort it when you need it sorted, not all the time.
Andreas Petersson
+2  A: 
erickson
Point of pedantry: Or more likely in this case, invokeinterface, as Comparable is an interface.
Tom Hawtin - tackline
+1  A: 

I assume that the slowdown is because of virtual table lookup for this method.

You shouldn't have to guess if this is true. Just pause it a few times, and you will catch it in the act. Display the call stack in its entirety, including calls into library routines.

My guess (which could be wrong) is that it's going through nine-yards of OLE-style invocation hoo-haw.

Mike Dunlavey