Is there any performance penalty for static if?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed May 15 22:13:18 UTC 2019


On Wednesday, May 15, 2019 4:03:39 PM MDT Ferhat Kurtulmuş via Digitalmars-
d-learn wrote:
> Hi,
>
> Maybe I already know the answer, but have to be sure about this.
> I am emulating this cpp code "int val = mat.at<int>(row, col)"
> like:
>
> T at(T)(int row, int col){
>          static if (T.stringof == "float"){
>              return getFloatAt(row, col);
>          } else static if (T.stringof == "double"){
>              return getDoubleAt(row, col);
>          } else static if (T.stringof == "int"){
>              return getIntAt(row, col);
>          } else static if (T.stringof == "ubyte"){
>              return getUCharAt(row, col);
>          } else static if (T.stringof == "byte"){
>              return getSCharAt(row, col);
>          } else static if (T.stringof == "short"){
>              return getShortAt(row, col);
>          }
>      }
> This works as expected, and I know conditions of "static if" is
> determined at compile time  and I assume no speed penalty here?

If you really want to see what happens (for any piece of code), then you can
look at the generated assembly, but static if is completely a compile-time
construct. It affects which code ends up in the binary. For instance, if
your at function there were instantiated with double, then the resulting
function would be

T at(int row, int col)
{
    return getDoubleAt(row, col);
}

None of the rest of the code would be there. static if is just a tool for
controlling code generation. It _does_ increase compile times (albeit not
much), because it has to be processed at compile time, but it does not exist
in any way shape or form at runtime and thus can only affect runtime by
affecting what code gets compiled in.

- Jonathan M Davis






More information about the Digitalmars-d-learn mailing list