通過預先分配堆內存並遞增填充,性能有很大提高嗎?優化:在多個對象使用之前預先分配一堆堆內存 - GAINS?
考慮以下這個非常簡單的例子:
byte * heapSpace = malloc (1 000 000);
int currentWriteSpot = 0;
struct A {
int x;
byte * extraSpace;
int extraSpaceLength;
};
//a1 needs 10 bytes of extra storage space:
A a1;
a1.x = 2;
a1.extraSpace = heapSpace + currentWriteSpot;
a1.extraSpaceLength = 10;
currentWriteSpot += 10;
//a2 needs 120 bytes of extra storage space:
A a2;
a2.x = 24;
a2.extraSpace = heapSpace + currentWriteSpot;
a2.extraSpaceLength = 120;
currentWriteSpot += 120;
// ... many more elements added
for (...) {
//loop contiguously over the allocated elements, manipulating contents stored at "extraSpace"
}
free (heapSpace);
VS:
...
a1.extraSpace = malloc (10);
a2.extraSpace = malloc (120);
a3...
a4...
...
//do stuff
free (a1.extraSpace);
free (a2.extraSpace);
free ...
free ...
free ...
或者這可能只是在性能上沒有顯著的收益增加了複雜性?
謝謝大家!
肯定是內存管理器會爲你做到這一點? – 2011-03-07 22:15:40
你在C或C++嗎? – Puppy 2011-03-07 22:53:43
代碼示例本來是模糊的,但我會實際上是在C++中,Windows XP,Win7的合作,並建立Linux的變種 – 2011-03-07 22:59:31