Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can using unsigned short be slower than using int?

Tags:

c++

types

On this webpage, the comments on unsigned short state:

Used to reduce memory usage (although the resulting executable may be larger and probably slower as compared to using int

Why is this?

like image 679
George Tian Avatar asked Mar 02 '23 07:03

George Tian


1 Answers

I think the wording "probably slower" is too hard.

A theoretical fact is:

Calculations are done with at least int size, e.g.

short a = 5;
short b = 10;
short c = a + b;

This code snippet contains 3 implicit conversions. a and b are converted to int and added. The result is converted back from int to short. You can't avoid it. Arithmetic in C++ uses at least int size. It's called integer promotion.

In practice most conversions will be avoided by the compiler. And the optimizer will also remove many conversions.

like image 155
Thomas Sablik Avatar answered Mar 17 '23 12:03

Thomas Sablik