开发人员在编写代码时如何认真考虑使用16位整数?自从我编程以来,我一直在使用32位整数,我真的不考虑使用16位.
它很容易声明一个32位int,因为它是大多数语言的默认值.
除了保存一点点内存之外,使用16位整数的好处是什么?
既然我们有汽车,我们不会走路或骑马,但我们仍然会走路和骑马.
这些天不太需要使用短裤.在很多情况下,磁盘空间的成本和RAM的可用性意味着我们不再需要像20年前那样从计算机中挤出最后一点存储空间,因此我们可以牺牲一点存储效率来节省关于开发/维护成本.
但是,如果使用大量数据,或者我们正在使用具有小内存的系统(例如嵌入式控制器),或者当我们通过网络传输数据时,使用32或64位来表示16位值只是浪费存储器/带宽.你有多少记忆并不重要,浪费一半或四分之三只会是愚蠢的.
我对相对性能很感兴趣,因此我编写了这个小测试程序来对分配、使用和释放 int 和短格式的大量数据的速度进行非常简单的测试。
我多次运行测试,以防缓存等受到影响。
#include <iostream>
#include <windows.h>
using namespace std;
const int DATASIZE = 1000000;
template <typename DataType>
long long testCount()
{
long long t1, t2;
QueryPerformanceCounter((LARGE_INTEGER*)&t1);
DataType* data = new DataType[DATASIZE];
for(int i = 0; i < DATASIZE; i++) {
data[i] = 0;
}
delete[] data;
QueryPerformanceCounter((LARGE_INTEGER*)&t2);
return t2-t1;
}
int main()
{
cout << "Test using short : " << testCount<short>() << " ticks.\n";
cout << "Test using int : " << testCount<int>() << " ticks.\n";
cout << "Test using short : " << testCount<short>() << " ticks.\n";
cout << "Test using int : " << testCount<int>() << " ticks.\n";
cout << "Test using short : " << testCount<short>() << " ticks.\n";
cout << "Test using int : " << testCount<int>() << " ticks.\n";
cout << "Test using short : " << testCount<short>() << " ticks.\n";
}
Run Code Online (Sandbox Code Playgroud)
这是我的系统上的结果(运行 windows7 64 位的 64 位四核系统,但该程序是在发布模式下使用 VC++ Express 2010 beta 构建的 32 位程序)
Test using short : 3672 ticks.
Test using int : 7903 ticks.
Test using short : 4321 ticks.
Test using int : 7936 ticks.
Test using short : 3697 ticks.
Test using int : 7701 ticks.
Test using short : 4222 ticks.
Run Code Online (Sandbox Code Playgroud)
这似乎表明,至少在某些情况下,当数据量较大时,使用 Short 代替 int具有显着的性能优势。我意识到这远不是一个全面的测试,但有一些证据表明它们不仅使用更少的空间,而且至少在某些应用程序中处理速度也更快。