memcpy vs slice copy

bearophile bearophileHUGS at lycos.com
Sat Mar 14 20:50:58 PDT 2009


While doing some string processing I've seen some unusual timings compared to the C code, so I have written this to see the situation better.
When USE_MEMCPY is false this little benchmark runs about 3+ times slower:

import std.c.stdlib: malloc;
import std.c.string: memcpy;
import std.stdio: writefln;

const bool USE_MEMCPY = true;

void main() {
    const int N = 100_000_000;

    auto h = "hello\n";
    char* ptr = cast(char*)malloc(N * h.length);
    char* p = ptr;

    for (int i; i < (h.length * N); i += h.length) {
        static if (USE_MEMCPY)
            memcpy(p, h.ptr, h.length);
        else
            p[0 .. h.length] = h;

        p += h.length;
    }

    if (N <= 100) // to see if it works decrease N
        writefln(ptr[0 .. N * h.length]);
}

As usual with benchmarks I may be missing things (especially because now it's quite late here), so keep eyes open.

Bye,
bearophile



More information about the Digitalmars-d mailing list