我正在制作一个将要使用许多动态创建对象(光线追踪)的应用程序。我不是一次又一次地使用[new],而是认为我只是制作一个简单的内存系统来加快速度。在这一点上它非常简单,因为我不需要太多。新增内存大量增加
我的问题是:当我运行这个测试应用程序,使用我的内存管理器使用的内存正确的金额。但是当我使用[new]运行相同的循环时,它会使用2.5到3倍的内存。有没有我在这里没有看到的东西,或者[新]是否会产生巨大的开销?
我使用VS 2010 Win7上。此外,我只是使用任务管理器来查看进程内存使用情况。
template<typename CLASS_TYPE>
class MemFact
{
public:
int m_obj_size; //size of the incoming object
int m_num_objs; //number of instances
char* m_mem; //memory block
MemFact(int num) : m_num_objs(num)
{
CLASS_TYPE t;
m_obj_size = sizeof(t);
m_mem = new char[m_obj_size * m_num_objs);
}
CLASS_TYPE* getInstance(int ID)
{
if(ID >= m_num_objs) return 0;
return (CLASS_TYPE*)(m_mem + (ID * m_obj_size));
}
void release() { delete m_mem; m_mem = 0; }
};
/*---------------------------------------------------*/
class test_class
{
float a,b,c,d,e,f,g,h,i,j; //10 floats
};
/*---------------------------------------------------*/
int main()
{
int num = 10 000 000; //10 M items
// at this point we are using 400K memory
MemFact<test_class> mem_fact(num);
// now we're using 382MB memory
for(int i = 0; i < num; i++)
test_class* new_test = mem_fact.getInstance(i);
mem_fact.release();
// back down to 400K
for(int i = 0; i < num; i++)
test_class* new_test = new test_class();
// now we are up to 972MB memory
}
您的程序不完整。无论如何,我们可能都不想要这一切。 – 2011-05-31 18:30:17
这是什么平台? – 2011-05-31 18:35:03
对不起。我试图编辑史诗格式失败,但有人编辑我之前,我想锁定我的更改。它不喜欢我把它放在那里的方式 – Veaviticus 2011-05-31 18:36:28