Proposal: takeFront and takeBack

Jonathan M Davis jmdavisProg at gmx.com
Wed Jul 4 11:55:01 PDT 2012


On Wednesday, July 04, 2012 06:42:32 Ed McCardell wrote:
> On 07/04/2012 04:50 AM, Jonathan M Davis wrote:
> > But reducing code was never my concern (nor Dmitry's in considering
> > proposing essentially the same thing). It's efficiency that's the problem
> > - particularly with strings. IIRC, with the tests that I ran, it took
> > about 33% longer to use front and popFront separately than it did to use
> > consumeFront with strings.
> Does the speed difference show up in both GDC and DMD? (If you can post
> some test code, I can check GDC on linux).

I've never used either of those, but due to the nature of the operations in 
question, I believe that I can guarantee thate there will be a speed difference 
on them as well. If you want to test it yourself, you can use this code and 
just adjust the string being tested (and the number of iterations as well - 
particularly if your machine is slower than mine):

import std.array;
import std.conv;
import std.datetime;
import std.range;
import std.stdio;
import std.traits;


auto consumeFront(R)(ref R range)
    if(isInputRange!R && !isNarrowString!R)
{
    assert(!range.empty);
    auto retval = range.front;
    range.popFront();
    return retval;
}

auto consumeFront(R)(ref R range)
    if(isNarrowString!R)
{
    import std.utf;
    assert(!range.empty);
    size_t index = 0;
    auto retval = decode(range, index);
    range = range[index .. $];
    return retval;
}

void main()
{

    //auto orig = "ウェブサイト@La_Verité.com";
    auto orig = "hello world";
    //auto orig = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    void f1()
    {
        auto arr = orig;

        while(!arr.empty)
        {
            auto f = arr.front;
            arr.popFront();
        }
    }

    void f2()
    {
        auto arr = orig;

        while(!arr.empty)
            auto f = arr.consumeFront();
    }

    auto result = benchmark!(f1, f2)(10_000_000);
    writeln(to!Duration(result[0]));
    writeln(to!Duration(result[1]));
}

On rerunning this, with -release -O -inline, it seems to take about 70% as 
long with consumeFront, and without those flags, it takes about 80% as long.

- Jonathan M Davis


More information about the Digitalmars-d mailing list