在C中使用char作为小整数的优点/缺点 [英] Pros/cons to using char for small integers in C
问题描述
对C中的小整数使用 char
有什么不利吗?除了占用/内存优势之外还有什么优势吗?
Is there any disadvantage to using char
for small integers in C? Are there any advantages other than the occupancy/memory benefit?
特别是,处理器可能会在 char上处理整数运算
长
/ 短
) int
?
In particular, is the processor likely to cope with integer arithmetic on a char
better or worse than it would on a (long
/short
) int
?
我知道这将是处理器/系统/编译器特定的,但我希望在一般情况下得到答案,或者至少,32位Windows和Solaris的一般情况,是我目前正在研究的系统。我还假设已经处理了溢出/回绕问题等问题。
I know this will be processor/system/compiler specific, but I'm hoping for an answer in the general case, or, at least, the general case for 32-bit Windows and Solaris, being the systems I'm currently working on. I'm also assuming that things like overflow/wraparound issues have already been dealt with.
更新:Visual Studio 6.0实际上没有 stdint .h
正如Christoph所建议的那样。 Windows上的一个小基准测试(VS 6.0,调试版本,32位)和一些堆叠循环给出 int
和 long
提供类似的性能,大约是 char
的两倍。使用gcc在Linux上运行相同的测试同样将 int
和 long
视为相似,并且都比<$ c $更快c> char ,虽然差别不太明显。
Update: Visual Studio 6.0 doesn't actually have stdint.h
as suggested by Christoph. A little benchmarking on Windows (VS 6.0, debug build, 32-bit) with a handful of stacked loops gives int
and long
as providing similar performance, which is about twice as fast as char
. Running the same test on Linux with gcc similarly pegs int
and long
as similar, and both faster than char
, although the difference is less pronounced.
作为旁注,我没有花太多时间看,但是 stdint的第一个实现.h
for VS 6.0我发现(通过 Wikipedia )将 uint_fast8_t
定义为 unsigned char
,尽管在我的测试中看起来似乎比较慢。因此,正如Christoph正确建议的那样,故事的寓意:总是基准!
As a side note, I've not spent much time looking, but the first implementation of stdint.h
for VS 6.0 I found (via Wikipedia) defines uint_fast8_t
as unsigned char
, despite this seeming to be slower in my tests at least. Thus, the moral of the story, as Christoph rightly suggested: always benchmark!
推荐答案
C99增加了所谓的最快最低限度-width整数类型来解决这个问题。对于您感兴趣的范围,类型将是 int_fast8_t
和 uint_fast8_t
,可在<$中找到c $ c> stdint.h 。
C99 added so-called 'fastest' minimum-width integer types to solve this problem. For the range you're interested in, the types would be int_fast8_t
and uint_fast8_t
, which can be found in stdint.h
.
请记住,可能没有性能提升(内存消耗的增加甚至可能会减慢速度下);一如既往,基准!不要过早地或仅仅根据应该起作用的可能有缺陷的假设进行优化。
Keep in mind that there might be no performance gain (the increase in memory consumption might even slow things down); as always, benchmark! Don't optimize prematurely or solely on potentially flawed assumptions of what should work.
这篇关于在C中使用char作为小整数的优点/缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!