Efficient way to pass struct as parameter

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jan 2 23:27:22 UTC 2018


On Tue, Jan 02, 2018 at 10:17:14PM +0000, Johan Engelen via Digitalmars-d-learn wrote:
[...]
> Passing by pointer (ref is the same) has large downsides and is
> certainly not always fastest. For small structs and if copying is not
> semantically wrong, just pass by value.

+1.


> More important: measure what bottlenecks your program has and optimize
> there.
[...]

It cannot be said often enough: premature optimization is the root of
all evils.  It makes your code less readable, less maintainable, more
bug-prone, and makes you spend far too much time and energy fiddling
with details that ultimately may not even matter, and worst of all, it
may not even be a performance win in the end, e.g., if you end up with
CPU cache misses / excessive RAM roundtrips because of too much
indirection, where you could have passed the entire struct in registers.

When it comes to optimization, there are 3 rules: profile, profile,
profile.  I used to heavily hand-"optimize" my code a lot (I come from a
strong C/C++ background -- premature optimization seems to be a common
malady among us in that crowd).  Then I started using a profiler, and I
suddenly had that sinking realization that all those countless hours of
tweaking my code to be "optimal" were wasted, because the *real*
bottleneck was somewhere else completely.  From many such experiences,
I've learned that (1) the real bottleneck is rarely where you predict it
to be, and (2) most real bottlenecks can be fixed with very simple
changes (sometimes even a 1-line change) with very big speed gains,
whereas (3) fixing supposed "inefficiencies" that aren't founded on real
evidence (i.e., using a profiler) usually cost many hours of time, add
tons of complexity, and rarely give you more than 1-2% speedups (and
sometimes can actually make your code perform *worse*: your code can
become so complicated the compiler's optimizer is unable to generate
optimal code for it).


T

-- 
MSDOS = MicroSoft's Denial Of Service


More information about the Digitalmars-d-learn mailing list