3

Let say that I have a function more or less like this (pseudo code, not a real one so please do not consider how much it is useless :P ):

template <typename T>
T function()
{
 std::vector<size_t> a = {1, 2, 3, 4, 5};
 T r = 0;
 for (size_t i=0; i<a.size(); ++i)
 {
  r += static_cast<T>(a[i]);
 }
 return r;
}

Now i'd like to know if compiler will optimize out static_cast if T=size_t. I know that there is not much todo if T will be an int but will it be optimized out or solved on compile time?

Michal W
  • 793
  • 8
  • 24
  • 2
    In most cases (aside from call to constructors and such), no code is generated by `static_cast`, so there is nothing to optimize. It's a compile-time hint to the compiler to interpret a type differently. If the types can't be converted explicitly (for example `static_cast(std::vector())`) the compiler issues an error. – rashmatash Jul 21 '14 at 11:02
  • @thokra - it was intended :) – Michal W Jul 21 '14 at 11:06
  • @rashmatash - so static_cast shouldn't generate any runtime performance hit at all? Even if I cast size_t to double? Strange... – Michal W Jul 21 '14 at 11:07
  • 2
    @rashmatash: What about stuff like float to int? Disassembly with GCC definitely shows a call to `cvttss2si`. Can you please refer to the corresponding spec passage? – thokra Jul 21 '14 at 11:09
  • 1
    @thokra - that is what i was thinking about, I3E standard keep bits in very different way than ints so that why i ask rashmatash - you can't just copy bits to register. Thanks for this post thokra :) Anyway we are getting out of the road a bit - question was about optimization if ... and not "do static_cast generate sth in code". – Michal W Jul 21 '14 at 11:12
  • 1
    For basic types (e.g. int, float, double) when the data type requires a different format/register then some load/store instructions will be generated. For example a "move to" instruction will load the value of the int to a float. However, when you'd write `static_cast(37)` no extra code is generated, normally. – rashmatash Jul 21 '14 at 11:18
  • 3
    @rashmatash Well, that's a case of constant folding. In general an `int` to `float` conversion will require at least one opcode. – aschepler Jul 21 '14 at 11:27
  • Ok, great. So going this way I can think that if T=size_t then there will be sth like size_t r = static_cast(a[i]) which try to cast size_t to size_t so... no extra code will be generated so... it will be optimized out during compilation, yes? – Michal W Jul 21 '14 at 11:39

1 Answers1

1

For native types any modern compiler should be optimizing a static_cast to the same type. Here's another answer to the same question which suggests types with non-trivial copy constructors may induce an overhead.

Can static_cast to same type introduce runtime overhead?

Community
  • 1
  • 1
Brandon Kohn
  • 1,612
  • 8
  • 18