Reputation: 6042
I want to shift an unsigned type (e.g. size_t) by a non-negative number of (binary) digits / places to the left/right, e.g.
size_t x;
x << non_const_expr
under the assumptions that the value of non_const_expr
fits in an (unsigned) int
and never
causes undefined behavior (its value is non-negative and does not exceed the number of digits in x
). (Note that the value is unknown at compile-time.)
Suppose that such a shift occurs in a performance-critical section (e.g. it is the only operation in the innermost loop). My trilemma is which type the right operand (the return type of non_consts_expr
) should ideally be for the fastest shift operation:
unsigned int
seems most readable/intuitive)int
(AFAIK int
is the native (and fastest?) type on the platform, while unsigned
could be implemented in a less efficient manner`)size_t
in this case)Does it matter at all? If yes, which one generally results in the fastest code?
Upvotes: 2
Views: 783
Reputation: 57678
The optimal performance of a left or right shift is when the RHS is a positive numerical constant.
Otherwise, it's processor dependent.
I suggest you code up different examples and look at the assembly language code generated by the compiler. You may also want to adjust the optimization settings also to see if they have any influence.
On the ARM7 processor, a shift operation may occur with a load register instruction; otherwise it would load a value then use a shift assembly instruction.
If you use a variable for the RHS, you are looking at the minimal operations:
The truth will be in the assembly language listing.
Optimizations at this level often don't produce negligible performance gains. Usually bigger gains can be found by optimizing design or code elsewhere.
Upvotes: 1