static array literal syntax request: auto x=[1,2,3]S;

timotheecour thelastmammoth at gmail.com
Sat Jun 9 15:05:02 PDT 2012


(apologies for cross-posting here, I feel this is a better place 
to ask than in my original post where I only received 1 answer 
that seemed in favor of this:
http://d.puremagic.com/issues/show_bug.cgi?id=8008 which was 2 
months ago).

Please see to the original post above to see the proposal for the 
new syntax for static array litterals
(but please reply here).

Running some simple tests show that this is not just cosmetics 
and ease of use but would also lead to significantly reduced 
overhead when dealing with static array litterals vs raw C array 
litterals, as currently D static array litterals perform costly 
heap allocation as intermediate step (as shown in the resulting 
assembly).

Here's 2 identical programs in C and D, which, compiled with all 
optimization flags, result in 20x speedup for the C version (D 
takes 17 sec with dmd -O -release -inline -noboundscheck main).

-----
//main.d
import std.stdio,std.conv;
void main(){
	size_t n=100000000,z=0;i=0,j=0;
	for(i=0;i<n;i++){
		size_t[10] a=[i,i+1,i+2,i+3,i+4,i+5,i+6,i+7,i+8,i+9];
		for(j=0;j<9;j++){z+=a[j];}
	}
	writeln(z);
}
-----
//main.c
#include <stdio.h>
int main(){
	size_t n=100000000,z=0;i=0,j=0;
	for(i=0;i<n;i++){
		size_t a[10]={i,i+1,i+2,i+3,i+4,i+5,i+6,i+7,i+8,i+9};
		for(j=0;j<9;j++){z+=a[j];}
	}
	printf("%lu\n",z);
	return 0;
}
-----
Note, the same D program modified as follows runs about as fast 
as the C program:
size_t[10] a=void; a[0]=i; a[1]=i+1; 
a[2]=i+2;a[3]=i+3;a[4]=i+4;a[5]=i+5;a[6]=i+6;a[7]=i+7;a[8]=i+8;a[9]=i+9;

Having the new syntax auto 
a=[i,i+1,i+2,i+3,i+4,i+5,i+6,i+7,i+8,i+9]S would prevent the 
intermediate heap allocation and should be at least as fast as 
the C version, possibly faster if SSE instructions are used.

Finally, someone suggested somewhere else 
(http://www.digitalmars.com/d/archives/digitalmars/D/bugs/Issue_8008_New_static_array_literal_syntax_request_auto_x_1_2_3_S_39709.html) 
that this could be done in library code:
auto a = [1, 2, 3].toStatic;
however I don't see how that could be achieved, as by the time 
the array reaches the toStatic function, it is a dynamic array 
whose length is not known at compile time.
Also, his suggested syntax auto[$] a=[1,2,3] is not as good in my 
opinion as it prevents one from directly passing an (anonymous) 
static array to a function, eg my_fun([1,2,3]S) vs: auto[$] 
a=[1,2,3]; my_fun(a);

Thanks for your comments!



More information about the Digitalmars-d mailing list