Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of 'short' in C++

Tags:

c++

Why is it that for any numeric input we prefer an int rather than short, even if the input is of very few integers.

The size of short is 2 bytes on my x86 and 4 bytes for int, shouldn't it be better and faster to allocate than an int?

Or I am wrong in saying that short is not used?

like image 558
user225312 Avatar asked Dec 05 '09 07:12

user225312


2 Answers

CPUs are usually fastest when dealing with their "native" integer size. So even though a short may be smaller than an int, the int is probably closer to the native size of a register in your CPU, and therefore is likely to be the most efficient of the two.

In a typical 32-bit CPU architecture, to load a 32-bit value requires one bus cycle to load all the bits. Loading a 16-bit value requires one bus cycle to load the bits, plus throwing half of them away (this operation may still happen within one bus cycle).

like image 132
Greg Hewgill Avatar answered Sep 23 '22 11:09

Greg Hewgill


A 16-bit short makes sense if you're keeping so many in memory (in a large array, for example) that the 50% reduction in size adds up to an appreciable reduction in memory overhead. They are not faster than 32-bit integers on modern processors, as Greg correctly pointed out.

like image 33
Matthew Avatar answered Sep 19 '22 11:09

Matthew