ericg@ucschu.ucsc.edu (Eric Goodman) (02/02/91)
In article <1991Jan29.221121.20642@odin.corp.sgi.com> linton@sgi.com (Mark Linton) writes: > As for virtual functions, if you can't live with cost of a virtual function call > you are unlikely to be happy with the cost of a direct function call. A virtual > function call typically adds a few memory references on top of what is likely > a considerably more expensive operation, involving register save/restore and > a branch. There is more than the indirect reference. There is the virtual function table which must be maintained for each object. If you are dealing with many (thousands) of small (2-4 int) objects, by using virtual functions you are adding at least 25%-50% extra size to your objects (assuming ints and the index into the virtual function table to be equal in size - it's probably worse than that). This leads into my question: when I declare a class with virtual functions how much memory am I losing per object? I was originally given to understand that for each virtual function a class maintains an index into a virtual function table, meaning extra memory size required is roughly proportional to the number of virtual functions. But thinking about it, that sounds too inefficient, so it should be something like a pointer to a virtual function table is created, meaning each object created uses extra memory for having virtual functions, but the amount of memory lost per object is constant whether one or several virtual functions are used in the class. Who wants to straighten me out? E-mail replies appreciated, or post and e-mail (I don't always get postings). Thanks Eric Goodman, UC Santa Cruz ericg@ucschu.ucsc.edu ericg@ucschu.bitnet Eric_Goodman.staff@macmail.ucsc.edu ...!ucbvax!ucscc!ucschu!ericg
fuchs@it.uka.de (Harald Fuchs) (02/03/91)
ericg@ucschu.ucsc.edu (Eric Goodman) writes: >This leads into my question: when I declare a class with virtual functions >how much memory am I losing per object? >Who wants to straighten me out? E-mail replies appreciated, or post and >e-mail (I don't always get postings). Depends on the implementation. All implementations I know about do the following: - They create one virtual function table for every class with virtual functions (also for classes with base classes containing virtual functions). Note that there is only one table like that for all objects of that class, and the size of the table is proportional to the number of virtual functions in the inheritance DAG. - In every object of a class like that, they store a pointer to the virtual function table of that class. So you lose (on most machines) exactly four bytes per object. -- Harald Fuchs <fuchs@telematik.informatik.uni-karlsruhe.de> <fuchs@telematik.informatik.uni-karlsruhe.dbp.de> *gulp*