1

I have a function f which will be called hundreds of millions of times, and I was wondering is there any runtime performance difference between:

void f()
{
    int a = ...;
    size_t b = static_cast<size_t>(a);
}

and

void f()
{
    int a = ...;
    size_t b = a;
}

I heard somwhere that static_cast has to create a temp variable, which means it has a small cost.

I was wondering if implicit casting has the same performance impact.

Or, is static_cast the same as reinterpret_cast where it has 0 extra instructions?

  • You can check the generated assembly on places like [godbolt](https://godbolt.org/). I'm seeing the two versions compiling to the same thing. – Nathan Pierson Apr 10 '21 at 20:28
  • 1
    There is a nuance that the dupe doesn't address, namely if you `static_cast` to the same type as the implicit conversion, then there will be no difference whatsoever. But it *is* possible to generate additional code by `static_cast`ing to some unnatural type like `float` in this [example](https://gcc.godbolt.org/z/e8ceWK1jo). – rustyx Apr 10 '21 at 20:38

0 Answers0