I was looking at the answers of this question.
How can it be possible that instanceof
has turned out faster than a polymorphic call like equals
.
I was looking at the answers of this question.
How can it be possible that instanceof
has turned out faster than a polymorphic call like equals
.
I suppose, you are referring to this answer which should be downvoted to the ground instead of getting so much upvotes. First of all, any numbers posted without showing the actual code under test nor naming any benchmarking tool should be considered to be a (perhaps) interesting comment rather than a quality answer.
Second, this answer compares two entirely unrelated operations, a String
equality check and the instanceof
operator. That answer misleads the reader (like you) into thinking that it bears any finding about the cost of Java’s method dispatch, but there is no way to measure that cost in isolation. If you measure the cost of invoking a method doing work X (like String comparison), you’re basically measuring the costs of work X (the String comparison), rather than the invocation cost. Since instanceof
doesn’t perform a String comparison, it’s obvious that it does less work than calling String.equals
. Especially, as the implementation of String.equals(Object)
even does an instanceof
on the argument.
So it should not surprise you when calling String.equals
imposes more costs than doing a sole instanceof
operation, giving an answer to an entirely different question. The linked answer still is not sufficient to prove that this actually did happen. Measuring 80±17ms and 168±62ms for a loop of 10,000,000 iterations is a clear sign that the actual costs of the loop body are buried deep under statistical noise.
Besides all that, String.equals
can not even considered a polymorphic call.