Old problem with performance

Radu radu.racariu at void.space
Sun Feb 8 07:19:40 PST 2009


Weed wrote:
> (Has started here:
> http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=81359)
>
> To me still does not give rest performance of classes (in comparison
> with C++ or with D structs)
>
> I still think that it is a serious problem.
>
> Colleagues from our national D forum have asked to show it and I have
> written simple examples on D. I want to share with you too them.
>
> On my computer the code with structure (i.e. object by value) runs in 6
> times faster than a code with a class:
>
> $ time ./struct
>
> real    0m8.515s
> user    0m7.796s
> sys     0m0.016s
> $ time ./class
>
> real    0m52.185s
> user    0m40.543s
> sys     0m0.076s
>
> The code on C++ is also approximately in 6 times faster a code with
> classes on D. (I do not give an example on C++ because classes on C++
> work just as structures in D.)
>
> I think with it it is necessary to do something.
>
>
> Examples code:
>
> //========================
> struct C {
>     int i;
>     real[5] unused; // to prevent returning this object in registers
>
>     C opAdd( C src ) {
>         C ret;
>         ret.i = i + src.i;
>         return ret;
>     }
> }
>
> int main() {
>     C c1;
>     C c2;
>
>     // initialise i by "random" value to prevent compile-time calculation
>     c1.i = cast(int)&c1;
>     c2.i = 0;
>
>     for(int i = 0; i < 50_000_000; ++i)
>         c2 = c1 + c1 + c1;
>
>     return c2.i;
> }
>
> //========================
>
> class C {
>     int i;
>     real[5] unused; // to prevent returning this object in registers
>
>     C opAdd( C src ) {
>         auto ret = new C;
>         ret.i = i + src.i;
>         return ret;
>     }
> }
>
> int main() {
>     auto c1 = new C;
>     auto c2 = new C;
>
>     // initialise i by "random" value to prevent compile-time calculation
>     c1.i = cast(int)&c1;
>     c2.i = 0;
>
>     for(int i = 0; i < 50_000_000; ++i)
>         c2 = c1 + c1 + c1;
>
>     return c2.i;
> }
> //========================
>   
While nor so orthodox, this improves the situation a bit:

template stackAllocator(T) {
    new(size_t size, void* sp = alloca(T.classinfo.init.length)) {
        return sp;
    }

    delete(void* ptr) {
    }
}

final class C {
    int i;
    real[5] unused; // to prevent returning this object in registers

    C opAdd(C src) {
        auto ret = new C;
        ret.i = i + src.i;
        return ret;
    }

    mixin stackAllocator!(C);

}

Radu



More information about the Digitalmars-d mailing list