Saturday, 15 May 2010

In Java, does subclassing and overriding the same method cause runtime inefficiency? -



In Java, does subclassing and overriding the same method cause runtime inefficiency? -

i read somewhere, while ago - , don't recall where, subclassing several times , each time overriding same method, causes run-time inefficiency.

for example:

class a{protected myfunction(){}} class b extends a{@override myfunction(){}} class c extends b{@override myfunction(){}}

is true calling myfunction() within class "slower" ? remember author described inefficiency due pointer lookup had done in order access right overriding method.

to explain in bit more detail:

inside jvm's private representation each loaded class table of method pointers. when compile class x, methods xmethod1, xmethod2, xmethod3 assigned slots in table -- in same order. let's object has slots 0-10, x has slots 11, 12, , 13.

when define class y subclass of x, private representation y's slots 0-13 of it's method table copied x's method table. ymethod1, ymethod2, ymethod3 assigned slots 14, 15, , 16 in new table. 1 can phone call method index , right version.

now if class y defines it's own version of xmethod2, pointer version placed in method table of representation y's class @ slot 12, overlaying method pointer class x.

when create object instance, pointer class's private representation placed in instance header, so, when method called, method table can consulted , right method accessed (with method table index values having been compiled bytecodes).

so phone call function is: fetch private representation pointer object header, fetch table pointer in private representation, index table literal index, fetch method pointer, transfer command method.

interface methods: there several different implementations of phone call mechanism interfaces, suspect ours did and, instead of indexing "method table" used virtual calls, consult hashtable. rather searching using method name, pre-calculated method identifier used search hashtable , fetch method pointer, mechanism fast , compact.

again, mechanism not "care" how things subclassed/subinterfaced.

java

No comments:

Post a Comment