On 32-bit CPUs, is an 'integer' type more efficient than a 'short' type?

前端 未结 8 1604
离开以前
离开以前 2020-11-29 09:30

On a 32-bit CPU, an integer is 4 bytes and a short integer is 2 bytes. If I am writing a C/C++ application that uses many numeric values that will always fit within the pro

8条回答
  •  孤城傲影
    2020-11-29 10:16

    If you have a large array of numbers, then go with the smallest size that works. It will be more efficient to work with an array of 16 bit shorts than 32 bit ints since you get twice the cache density. The cost of any sign extension the CPU has to do to work with 16 bit values in 32 bit registers is trivially negligible compared to the cost of a cache miss.

    If you are simply using member variables in classes mixed with other data types then it is less clear cut as the padding requirements will likely remove any space saving benefit of the 16 bit values.

提交回复
热议问题