假设我们有 uint_least8_t var
,其中,假设地说,var
永远不会超过值 255。
我知道这不是编程的工作方式,“可能”和“曾经”是一种亵渎,但是,除了使代码复杂化并降低其可读性之外,是什么让始终使用固定宽度整数成为一个坏主意?
最佳答案
性能是另一个原因。
窄操作数需要额外的缩小/扩大指令。这不能总是在没有副作用的情况下被优化掉。有时,优化器不够智能,无法安全运行。
以下面这个人为的例子为例。
#include <iostream>
#include <chrono>
using namespace std;
using namespace std::chrono_literals;
int main()
{
auto tm1 = chrono::high_resolution_clock::now();
unsigned int n = 0;
unsigned int x = 0; // though, uint8_t would have been enough!
for (unsigned int i = 0; i < 1000000000; i++) {
n += (x * i);
x = (n + 1) & 0x7F;
}
auto tm2 = chrono::high_resolution_clock::now();
cout << n << ", " << (tm2 - tm1) / 1.0s << " s" << endl;
}
如果我们将 x
的类型从 unsigned int
更改为 uint8_t
,应用程序将变慢 15%(运行 2s 而不是 1.7s使用 GCC 7.2 -O3
完全优化编译时在 x86-64 上的时间。
用 32-bit 组装x
:
.L2:
imul eax, edx
inc edx
add ebx, eax
lea eax, [rbx+1]
and eax, 127
cmp edx, 1000000000
jne .L2
用 8-bit 组装x
:
.L2:
movzx eax, al ; owww!
imul eax, edx
inc edx
add ebp, eax
lea eax, [rbp+1]
and eax, 127
cmp edx, 1000000000
jne .L2
关于c++ - 是否有任何与可读性无关的原因不能每次都专门使用固定宽度的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53637492/