Array Operations: a[] + b[] etc.

John Colvin john.loughran.colvin at gmail.com
Thu Nov 22 03:25:30 PST 2012


On Wednesday, 21 November 2012 at 20:16:59 UTC, Walter Bright 
wrote:
> On 11/21/2012 10:41 AM, John Colvin wrote:
>> In what way does it become a performance problem?
>
> Allocating memory is always much, much slower than not 
> allocating memory.
>
> A design that forces allocating new memory and discarding the 
> old as opposed to reusing existing already allocated memory is 
> going to be far slower. In fact, the allocation/deallocation is 
> going to dominate the performance timings, not the array 
> operation itself.
>
> Generally, people who use array operations want them to be 
> really fast.

Well yes, of course, I thought you meant something more esoteric. 
I'm not suggesting that we replace the current design, simply 
extend it.

We'd have:

c[] = a[] + b[];
fast, in place array operation, the cost of allocation happens 
earlier in the code.

but also
c = a[] + b[];
a much slower, memory assigning array operation, pretty much just 
shorthand for
c = new T[a.length];
c[] = a[] + b[];

You could argue that hiding an allocation is bad, but I would 
think it's quite obvious to any programmer that if you add 2 
arrays together, you're going to have to create somewhere to put 
them... Having the shorthand prevents any possible mistakes with 
the length of the new array and saves a line of code.

Anyway, this is a pretty trivial matter, I'd be more interested 
in seeing a definitive answer for what the correct behaviour for 
the statement a[] = b[] + c[] is when the arrays have different 
lengths.


More information about the Digitalmars-d mailing list