string initialization question.

Jonathan M Davis jmdavisprog at gmail.com
Fri Jul 30 13:31:49 PDT 2010


On Friday, July 30, 2010 13:10:46 Steven Schveighoffer wrote:
> On Fri, 30 Jul 2010 15:56:36 -0400, Jonathan M Davis
> 
> <jmdavisprog at gmail.com> wrote:
> > On Friday, July 30, 2010 10:14:45 Steven Schveighoffer wrote:
> >> I think a function to do it is fine, like makeArray('-', 5);
> > 
> > Well, creating a function for producing an array literal and returning
> > it using
> > templates and string mixins wouldn't be all that hard, but if you want
> > to create
> > a dynamic array of arbitrary size at runtime, that's not going to work,
> > and a
> > makeArray() function would have exactly the same tools that you have to
> > create
> > an array of all the same value.
> 
> The function would call gc_malloc directly, which does not initialize the
> requested memory.  Actually, it would call a new run time function that I
> will write, which would initialize the array length also.

Well, if there's a function other than new to allocate GC memory, then 
makeArray() is quite doable. I've never dealt with anything but new. As far as 
I've been aware, you either use new for GC memory or malloc for non-GC memory. 
If there's a gc_malloc, then that would solve the problem and it would make good 
sense to do that with makeArray().

> 
> > So, it's not going to be any more efficient that
> > what you can do.
> > 
> > int[] a = new int[](x);
> > a[] = val;
> > 
> > _should_ be fairly easily optimized by the compiler and thus really
> > should be
> > optimized down to an initialization rather than an initialization and an
> > assignment.
> 
> It's not.  The only runtime functions available to the compiler look like
> this:
> 
> _d_newarrayT(TypeInfo ti, size_t length);

I guess that's one thing that comes of not really implementing it as a 
primitive. If there are enough such functions that would be properly optimizable 
had they actually been implemented as primitives, I would think that there would 
be some merit in finding a way to get the compiler to understand that it can do 
such optimizations. But I really don't know how all that works in dmd, so I have 
no idea how feasible that is.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list