我正在製作一個將要使用許多動態創建對象(光線追蹤)的應用程序。我不是一次又一次地使用[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