Tips and Tricks for D

Oskar Linde oskar.lindeREM at OVEgmail.com
Mon Jul 3 05:39:00 PDT 2006


Henrik Eneroth skrev:
> In article <e89hsn$1rvh$1 at digitaldaemon.com>, mclysenk at mtu.edu says...
>> (Not sure if this belongs in announcements)
>>
>> I've recently written up an article for intermediate and beginning D
>> programmers.  
>>
>> In it I discuss some basic tricks, covering:
>> + printf
>> + import scope
>> + struct initialization
>> + converting static arrays
>> + removing objects from dynamic arrays
>>
>> You can read it at http://www.assertfalse.com/articles/tricks.shtml .
>>
>> Any comments, questions, suggestions or other feedback is welcome!
>>
>> -Mikola Lysenko
>>
>>
> 
> Useful stuff! 
> A question about structs: I have in many cases used classes over structs because
> of the lack of constructors in structs. Performance-wise, is it always better to
> use structs over classes if you can? Or will a class where no virtual functions
> etc. are used be similar to a struct performance-wise?

A class will always have a bit more space overhead than a struct. Other 
than the implications of by-value vs by-reference there should not be 
any performance differences.

> Also, if structs are copy-by-value, could this lead to unnecessary memory
> allocations in those cases where just passing a reference (i.e. classes) would
> do? That is, would classes be a better choice in this case?

A pass-by-value struct will be allocated on the stack which generally 
costs nothing compared to a heap allocation. The cost of copying depends 
on the size of the struct. In general, passing large structs by value is 
expensive. Small structs may (or may not) be more efficiently passed by 
value. The actual speed difference of passing a small struct by value 
compared to by reference depends largely on how the struct is used and 
the ABI in use.

On some ABIs

struct XY { int x,y; }
int myfunc(XY p) { return p.x+p.y; }

will be identical to:

int myfunc(int x, int y) { return x+y; }

Returning a struct by value may be more expensive than passing it.

The only way to know for certain is to run the benchmarks yourself. I 
would guess that on x86, with its few registers, passing by reference 
could often be faster even for rather small structs. Does anyone have 
conclusive benchmark results and a rule of thumb here?

Rather than using a class, one could explicitly pass the struct by 
reference, by either an inout parameter or a pointer:

int myfunc(inout XY p)

int myfunc(XY *p)

Regards,

Oskar




More information about the Digitalmars-d-learn mailing list