Is adding 1 to a number repeatedly slower than adding everything at the same time in C++? -


if have number a, slower add 1 b times rather adding + b?

a += b; 

or

for (int = 0; < b; i++) {   += 1; } 

i realize second example seems kind of silly, have situation coding easier way, , wondering if impact performance.

edit: thank answers. looks posters know situation have. trying write function shift inputted character number of characters on (ie. cipher) if letter. so, want 1 char += number of shifts, need account jumps between lowercase characters , uppercase characters on ascii table, , wrapping z a. so, while doable in way, thought easiest keep adding 1 until end of block of letter characters, jump next 1 , keep going.

the language c++ not describe how long either of operations take. compilers free turn first statement second, , legal way compile it.

in practice, many compilers treat 2 subexpressions same expression, assuming of type int. second, however, fragile in seemingly innocuous changes cause massive performance degradation. small changes in type 'should not matter', statements nearby, etc.

it extremely rare first slower second, if type of a such += b slower operation calling += 1 bunch of times, be. example;

struct {   std::vector<int> v;   void operator+=( int x ) {     // optimize common case:     if (x==1 && v.size()==v.capacity()) v.reserve( v.size()*2 );     // grow buffer:     (int = 0; < x; ++i)       v.reserve( v.size()+1 );       v.resize( v.size()+1 );     }   } }; 

then a a; int b = 100000; a+=b; take longer loop construct.

but had work @ it.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -