struct vs class benchmark (was Re: Give struct the status it deserves)
Bruno Medeiros
daiphoenixNO at SPAMlycos.com
Sun Apr 2 03:51:35 PDT 2006
Derek Parnell wrote:
>
> But I think my example does show that classes (allocated on the heap)
> are slower than structs whether allocated on the heap or on the stack.
>
> Classes are slower than structs. Prove otherwise. I'm happy to be shown
> that I'm wrong.
>
> --Derek Parnell
> Melbourne, Australia
Now this is odd. I didn't expect classes on the heap to be much slower
than structs on the heap. After all, what is the extra overhead of classes?
It has the size overhead of having 2 more pointers (for ClassInfo and
for the monitor) and the overhead of initializing those pointers when
instantiating a class. Anything else? I thought not, however, I tried to
run a test (see code below), where I would simulate a class creation
with a struct, adding that overhead, yet the struct version is still
twice as fast (with or without optimization)! Why is that?? The best
that I could find was by looking at the assembly code, and that in the
class version a _d_newclass function is called instead of _d_new for the
struct version, yet does _d_newclass do more than _d_new other than just
initialize the pointers?
// -------------- code starts -------------------
private import std.c.stdio;
private import std.c.time;
private import std.stdio;
const static uint n = 100000000;
struct PointStruct
{
void * classinfo;
void * monitor;
void Construct(void *newclassinfo) {
this.classinfo = newclassinfo;
this.monitor = cast(void *) 0x98765;
}
}
void doitStruct()
{
PointStruct *p = new PointStruct;
p.Construct(cast(void *) 0x12345678);
}
final class PointClass
{
}
void doitClass()
{
PointClass p = new PointClass;
}
int main()
{
writefln(PointClass.classinfo.init.length," : ", PointStruct.sizeof);
clock_t time1 = clock();
for (uint i = 0; i < n; ++i)
{
version(test_struct_heap) {
doitStruct();
}
version(test_class_heap) {
doitClass();
}
}
double seconds = (clock() - time1);
seconds /= CLOCKS_PER_SEC;
writefln("Testing operation took %ss", seconds);
return 0;
}
// -------------- code ends -------------------
sh-2.04$ build main -version=test_struct_heap -Tbtsh -full
c:\devel\D.tools\dmd\bin\..\..\dm\bin\link.exe
main,btsh.exe,,user32+kernel32,btsh.def/noi;
sh-2.04$ build main -version=test_class_heap -Tbtch -full
c:\devel\D.tools\dmd\bin\..\..\dm\bin\link.exe
main,btch.exe,,user32+kernel32,btch.def/noi;
sh-2.04$ time ./btsh.exe
8 - 8
Testing operation took 18.204s
real 0m18.328s
user 0m0.015s
sys 0m0.015s
sh-2.04$ time ./btch.exe
8 - 8
Testing operation took 42.516s
real 0m42.625s
user 0m0.015s
sys 0m0.015s
--
Bruno Medeiros - CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D
More information about the Digitalmars-d
mailing list