1

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

Dani
  • 4,267
  • 4
  • 29
  • 37

4 Answers4

4

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
  • 16,248
  • 11
  • 59
  • 91
  • 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 Mar 10 '09 at 17:36
  • 1
    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 Mar 11 '09 at 10:49
2

No, you can't force static invocation in this case.

An instance method can be invoked "non-virtually" by the invokespecial instruction. This instruction is used when the target is known at compile time, like a constructor or a private method. In other cases—even when the target method is final—the invokevirtual or invokeinterface instructions are used.

erickson
  • 265,237
  • 58
  • 395
  • 493
1

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.

Community
  • 1
  • 1
amit
  • 10,612
  • 11
  • 61
  • 60
0

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
  • 40,059
  • 14
  • 91
  • 135