以文本方式查看主题

-  中文XML论坛 - 专业的XML技术讨论区  (http://bbs.xml.org.cn/index.asp)
--  『 C/C++编程思想 』  (http://bbs.xml.org.cn/list.asp?boardid=61)
----  char, string, vector的内存使用比较  (http://bbs.xml.org.cn/dispbbs.asp?boardid=61&rootid=&id=69832)


--  作者:卷积内核
--  发布时间:11/25/2008 5:14:00 PM

--  char, string, vector的内存使用比较
#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小内存导致内存消耗明显增多。


--  作者:oldnwind
--  发布时间:12/24/2008 11:03:00 AM

--  
请教楼主:
测试结果中,有关内存使用时通过什么工具还是没贴出来的部分代码完成的?


这种凡有疑问必亲自测试/体验的治学态度很值得学习!


--  作者:gtict
--  发布时间:12/31/2008 12:29:00 PM

--  
顶下楼上的,内存怎么测出来的还没说
W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
10,109.380ms