Optimize my code =)

Craig Dillabaugh cdillaba at cg.scs.carleton.ca
Fri Feb 14 09:06:23 PST 2014


On Friday, 14 February 2014 at 16:47:32 UTC, John Colvin wrote:
> On Friday, 14 February 2014 at 16:40:31 UTC, Craig Dillabaugh 
> wrote:
>> On Friday, 14 February 2014 at 16:00:09 UTC, Robin wrote:
>>>
>>> this(size_t rows, size_t cols) {
>>> 	this.dim = Dimension(rows, cols);
>>> 	this.data = new T[this.dim.size];
>>> 	enum nil = to!T(0);
>>> 	foreach(ref T element; this.data) element = nil;
>>> }
>>>
>> I am no expert at optimizing D code, so this is a bit of a 
>> shot in the dark, but does your speed improve at all if you 
>> replace:
>>
>>> 	this.data = new T[this.dim.size];
>>
>> with:
>>
>> this.data.length = this.dim.size
>
> Why would that make a difference here? They're (almost) 
> identical are they not? Certainly the body of the work, the 
> allocation itself, is the same.

Well, in my defense I did start with a disclaimer.  For some 
reason I thought using .length was the proper way to size arrays. 
   It is likely faster if you are resizing an existing array 
(especially downward), but in this case new memory is being 
allocated anyway.

In fact I ran some tests (just allocating a matrix over and over) 
and it seems using new is consistently faster than using .length 
(by about a second for 50000 matrices).  Shows how much I know.



More information about the Digitalmars-d-learn mailing list