Passing array as const slows down code?
Steven Schveighoffer
schveiguy at yahoo.com
Fri Apr 27 08:18:26 PDT 2012
On Fri, 27 Apr 2012 11:12:07 -0400, Joseph Rushton Wakeling
<joseph.wakeling at webdrake.net> wrote:
> Hello all,
>
> A surprise today when tweaking some code.
>
> I have a function which takes as input an array of values (the values
> are a custom struct). So, in pseudocode, it's something like this:
>
> struct MyStruct
> {
> size_t x;
> size_t y;
> double z;
> }
>
> void foo(MyStruct[] input)
> {
> ...
> }
>
> Since the input isn't modified, I thought I'd tag it as const[1]:
>
> void foo(const MyStruct[] input) { ... }
>
> ... but this turned out to noticeably slow down the program.
> (Noticeably as in, a 25-second as opposed to 23-second running time,
> consistently observed on repeated trials of different code versions.)
>
> I'm surprised by this as I would have thought if anything tagging a
> variable as const would if anything have increased the speed, or at
> worst left it the same as before.
>
> Can anyone explain why? It's no big deal, but I'm curious.
const should not affect code generation *at all*, except for name mangling
(const MyStruct is a different type from MyStruct), and generating an
extra TypeInfo for const MyStruct and const MyStruct[]. Const is purely a
compile-time concept.
This cannot account for an extra 2 seconds. Something else is happening.
Without more of your code, nobody can give a definitive answer except it
is not supposed to affect it.
-Steve
More information about the Digitalmars-d-learn
mailing list