(no subject)

coxalan coxalan at web.de
Sun Oct 14 05:44:17 PDT 2007


Hello!

I realized that this code: 

int func() {
    int res;
    int[] g;
    g.length = 10;
    foreach(v; g) {
        res += v;
    }
    return res;
}

void main() {
    for(int i=0; i<10000000; i++) {
        func;
    }
}

runs about 7 times slower than this one:

class Funcclass {
    int[] g;

    this() {
        g.length = 10;
    }

    int func() {
        int res;
        foreach(v; g) {
            res += v;
        }
        return res;
    }
}

void main() {
    auto fc = new Funcclass;
    for(int i=0; i<10000000; i++) {
        fc.func;
    }
}

The compilation was done with -O -release.
The difference comes from all the memory-allocating and garbage collecting in the first case.

My question is:
Is it the default solution to put the function 'func' and the array 'g' as members into a common class?
Or are there other / more elegant solutions for this?

Thanks!


More information about the Digitalmars-d-learn mailing list