string initialization question.

Steven Schveighoffer schveiguy at yahoo.com
Mon Aug 2 04:56:43 PDT 2010


On Fri, 30 Jul 2010 19:41:03 -0400, Justin Spahr-Summers  
<Justin.SpahrSummers at gmail.com> wrote:

> On Fri, 30 Jul 2010 16:30:17 -0700, Jonathan M Davis
> <jmdavisprog at gmail.com> wrote:
>> On Friday, July 30, 2010 14:13:15 dcoder wrote:
>> > If I'm writing a program that pretty prints tree data, or output of  
>> sql,
>> > like Oracle's sqlplus, or postgres equivalent, I find having such a
>> > utility function/constructor a pretty handy feature.
>> >
>> > I don't know where such a tool should finally be placed in D, but I  
>> having
>> > it available as a library or as part of the language would be great.   
>> It
>> > seems like a lot of other languages have it like python, perl, C++,  
>> and
>> > Java.  So it can't be that useless.
>>
>> Well, I certainly have no problem with a function like makeArray()  
>> existing.
>> It's just that it's one of those functions that I've never found  
>> useful, and I
>> don't think that I've ever seen anyone use it in code.

That's because it's not a trivial function to write :)  One has to have  
intimate knowledge of the runtime and understand how to properly allocate  
a block for this purpose.

Basically, there have been code instances of the form:

T[] x = new T[n];
x[] = initval;

Because that's the only way to do it.  Offer a function like makeArray,  
and why *wouldn't* you change to it?  I prefer a single  
line/initialization anyways.

> I agree with this sentiment. I think the feature is pretty niche to
> begin with, and the compiler should be able to optimize out the
> initialization in the sample I gave previously. D is indeed a systems
> language, but I (and I'm sure others) would like to use it in a high-
> level way, where I can write natural, straightforward code and expect
> the compiler to do the Right Thing.

I just find the syntax awkward:

char[] divider = new char[5]; // hey, compiler I'm initializing divider
divider[] = '-'; // OOHHH got you there, I wasn't done yet :)

It just seems natural that I should be able to do this in one line.   
Having the compiler optimize isn't a bad thing, but relying on the  
optimization because "we can't find a better way" seems crappy to me.

> Besides, performance is not an applicable argument for this use case.
> Even if the array initialization is compiled into the binary, the amount
> of time it would take is infinitesimal. If someone's trying to
> initialize a 100,000 element array to some specific value, they're
> likely going to write their own makeArray() anyways.

The performance improvement is certainly a smaller argument compared to  
the syntax.  But it is a nice bonus.  There are more significant  
performance bugs in initialization of static arrays using array literals.

-Steve


More information about the Digitalmars-d-learn mailing list