#include <string>
#include <vector>
#pragma warning(disable : 4996)
using namespace std;
typedef unsigned long ulong;
#define STRING_ARRAY_VERSION 0
#define STATIC_CHAR_VERSION 1
#define CHAR_STAR_VERSION 2
#define STRING_VECTOR_VERSION 3
#define CHAR_STAR_VECTOR_VERSION 4
#define TEST_VERSION 0
#define NUM 10000
#define SIZE 10
int main()
{
switch(TEST_VERSION)
{
case STRING_ARRAY_VERSION:
{
string data[NUM];
for(ulong i = 0; i < NUM; i++)
data[i] = "aabb";
break;
}
case STATIC_CHAR_VERSION:
{
char data[NUM][SIZE];
for(ulong i = 0; i < NUM; i++)
strcpy(data[i], "aabb");
break;
}
case CHAR_STAR_VERSION:
{
char* data[NUM];
for(ulong i = 0; i < NUM; i++)
{
data[i] = new char[10];
strcpy(data[i], "aabb");
}
break;
}
case STRING_VECTOR_VERSION:
{
vector<string> data;
for(ulong i = 0; i < NUM; i++)
data.push_back("aabb");
break;
}
case CHAR_STAR_VECTOR_VERSION:
{
vector<char*> data;
for(ulong i = 0; i < NUM; i++)
{
char* p = new char[10];
strcpy(p, "aabb");
data.push_back(p);
}
}
}
while(1)
;
return 0;
}
------------------------------------------------------------------------------------------------------
测试结果:
string array: times - 10000 memory - 1740k VM - 828k
static char array: times - 10000 memory - 1740k VM - 820k
char* array: times - 10000 memory - 2292k VM - 1368k
string vector: times - 10000 memory - 1752k VM - 828k
char* vector: times - 10000 memory - 2340k VM - 1420k
可以看出,使用string以及vector或者静态分配数组,内存消耗是比较少的,多次new小内存导致内存消耗明显增多。