struct vs class benchmark (was Re: Give struct the status it

Derek Parnell derek at psych.ward
Sun Mar 26 21:08:00 PST 2006


On Mon, 27 Mar 2006 04:11:37 +0000 (UTC), Dave wrote:

> These run as the same speed on my system, which is pretty cool since the
> accessor function for class Point.x is vitual. If you finalize it the class
> version is actually faster. No doubt the OP has a point when you try to alloc.
> classes in a tight loop, and I'd agree that stack allocated classes would be
> great, but if you can work around the allocation bottleneck then classes tend to
> be faster and easier to code because they are passed around by reference w/o
> pointer syntax.

I wasn't so sure about the 'passed around' claim. So I amended my test to
pass the object and the results were almost identical. So it appears that
passing structs is not an issue at all. In fact, if you look at the
generated machine code, the struct seems to be passed by reference even if
you code otherwise.

------------------
version(test_struct_stack)
{
    struct Point
    {
    	static int count = 0;
    	int x() { return 1; }
    }

    void upd(Point p)
    {
        Point.count += p.x;
    }
    void doit()
    {
        Point p;
        upd(p);
    }
    const static char[] Title = "STACK STRUCTS";
}

version(test_struct_heap)
{
    struct Point
    {
    	static int count = 0;
    	int x() { return 1; }
    }

    void upd(Point p)
    {
        Point.count += p.x;
    }
    void doit()
    {
        Point *p = new Point;
        upd(*p);
    }
    const static char[] Title = "HEAP STRUCTS";
}

version(test_class)
{
    class Point
    {
    	static int count = 0;
    	int x() { return 1; }
    }

    void upd(Point p)
    {
        Point.count += p.x;
    }
    void doit()
    {
        Point p = new Point;
        upd(p);
    }
    const static char[] Title = "CLASSES";
}
-----------------------

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocracy!"
27/03/2006 4:02:10 PM



More information about the Digitalmars-d mailing list