Hello,

I have tried to measure how much would some simple task be faster in D than in C#. I ported some simple code from C# to D 1:1 almost without changes and C# code was faster. After eliminating causes one by one I have an example which shows where the problem is. If the function is outside of class code runs much faster. I'm obviously doing something wrong and would appreciate any help with this.

Here is the code:

import std.stdio;
import std.conv;
import std.datetime;

public float getTotal(string s, int add)
{
        float result = add;
        for (int j = 0; j < s.length; j++)
        {
                result += s[j];
        }
        return result;
}

class A
{
        public float getTotal(string s, int add)
        {
                float result = add;
                for (int j = 0; j < s.length; j++)
                {
                        result += s[j];
                }
                return result;
        }
}

void main(string[] args)
{
        StopWatch sw;
        sw.start();

        int n = args.length == 2 ? to!int(args[1]) : 100000;

        string inputA = "qwertyuiopasdfghjklzxcvbnm0123456789";
        double total = 0;
        for (int i = 0; i < n; i++)
        {
                for (int ii = 0; ii < inputA.length; ii++)
                {
                        total += getTotal(inputA, i);
                }
        }
        sw.stop();
        writeln("direct call: ");
        writeln("total: ", total);
        writeln("elapsed: ", sw.peek().msecs, " [ms]");
        writeln();

    total = 0;
        auto a = new A();
        sw.reset();
        sw.start();
        for (int i = 0; i < n; i++)
        {
                for (int ii = 0; ii < inputA.length; ii++)
                {
                        total += a.getTotal(inputA, i);
                }
        }
        sw.stop();
        writeln("func in class call: ", total);
        writeln("total: ", total);
        writeln("elapsed: ", sw.peek().msecs, " [ms]");
}


here are the build configuration and execution times:

C:\projects\D\benchmarks\reduced problem>dub run --config=application --arch=x86_64 --build=release-nobounds --compiler=ldc2
Performing "release-nobounds" build using ldc2 for x86_64.
benchmark1 ~master: target for configuration "application" is up to date.
To force a rebuild of up-to-date targets, run again with --force.
Running .\benchmark1.exe
direct call:
total: 1.92137e+11
elapsed: 4 [ms]

func in class call: 1.92137e+11
total: 1.92137e+11
elapsed: 138 [ms]

Thanks in advance.

Reply via email to