Search code examples
ctypesmicro-optimization

Is there any performance difference in using int versus int8_t


My main question is, Is there any difference between int and int8_t for execution time ?

In a framework I am working on, I often read code where some paramteres are set as int8_t in function because "that particular parameter cannot be outside the -126,125 range".

In many places, int8_t is used for communication protocol, or to cut a packet into many fields into a __attribute((packed)) struct.

But at some point, it was mainly put there because someone thought it would be better to use a type that match more closely the size of the data, probably think ahead of the compiler.

Given that the code is made to run on Linux, compiled with gcc using glibc, and that memory or portability is not an issue, I am wondering if it is actually a good idea, performance-wise.

My first impression comes from the rule "Trying to be smarter than the compiler is always a bad idea" (unless you know where and how you need to optimize).

However, I do not know if using int8_t is actually a cost for performance (more testing and computation to match the int8_t size, more operations are needed to ensure the variable do not go out of bounds, etc.), or if it does improve performance in some way.

I am not good at reading simple asm, so I did not compile a test code into asm to try to know which one is better.

I tried to find a related question, but all discussion I found on int<size>_t versus int is about portability rather than performance.

Thanks for your input. Assembly samples explained or sources about this issue would be greatly appreciated.


Solution

  • int is generally equivalent of the size of register on CPU. C standard says that any smaller types must be converted to int before using operators on them.

    These conversions (sign extension) can be costly.

    int8_t a=1, b=2, c=3;
     ...
    a = b + c; // This will translate to: a = (int8_t)((int)b + (int)c);
    

    If you need speed, int is a safe bet, or use int_fast8_t (even safer). If exact size is important, use int8_t (if available).