[Issue 3383] New: newVoid

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Oct 9 10:08:58 PDT 2009


http://d.puremagic.com/issues/show_bug.cgi?id=3383

           Summary: newVoid
           Product: D
           Version: 2.033
          Platform: Other
        OS/Version: Windows
            Status: NEW
          Keywords: patch, performance
          Severity: enhancement
          Priority: P2
         Component: Phobos
        AssignedTo: nobody at puremagic.com
        ReportedBy: dsimcha at yahoo.com


--- Comment #0 from David Simcha <dsimcha at yahoo.com> 2009-10-09 10:08:58 PDT ---
D's new keyword for allocating dynamic arrays initializes the data to T.init. 
This is a perfectly reasonable safe default.  However, there should be an
obvious way to optimize this out if one is sure one doesn't need it, as there
is for static arrays.  Below is a proposed function, newVoid(), that should go
in std.array to allow such a thing.

import core.memory;

/**Gives the block attribute that a block containing type T should have,
 * i.e. scan or NO_SCAN.*/
GC.BlkAttr blockAttribute(T)() {
    if(typeid(T).flags & 1) {
        return cast(GC.BlkAttr) 0;
    } else {
        return GC.BlkAttr.NO_SCAN;
    }
}

unittest {
    assert(blockAttribute!(uint)() == GC.BlkAttr.NO_SCAN);
    assert(blockAttribute!(void*)() == cast(GC.BlkAttr) 0);
}

/**Returns a new array of type T w/o initializing elements.
 *
 * Examples:
 * ---
 * auto foo = newVoid!uint(5);
 * foreach(i; 0..5) {
 *     foo[i] = i;
 * }
 * ---
 */
T[] newVoid(T)(size_t length) {
    T* ptr = cast(T*) GC.malloc(length * T.sizeof, blockAttribute!(T)());
    return ptr[0..length];
}

unittest {
    // Mostly just see if this instantiates.
    auto foo = newVoid!uint(5);
    foreach(i; 0..5) {
        foo[i] = i;
    }

    foreach(i; 0..5) {
        assert(foo[i] == i);
    }
}

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list