A significant increase in performance, but you have to be very careful how the data will be used. If multithreading, you must provide data access control.
run this test:
#include <windows.h>
#include <stdio.h>
void StartTime (LARGE_INTEGER * pTime)
{
QueryPerformanceCounter (pTime);
}
ULONG EndTime (LARGE_INTEGER * pTime)
{
LARGE_INTEGER liDiff;
LARGE_INTEGER liFreq;
QueryPerformanceCounter (& liDiff);
liDiff.QuadPart - = pTime-> QuadPart;
liDiff.QuadPart * = 1000; // Adjust to milliseconds, shouldn't overflow ...
(void) QueryPerformanceFrequency (& liFreq);
return ((ULONG) (liDiff.QuadPart / liFreq.QuadPart));
}
void functionCalledLotsofTimesStatic (int size)
{
static int * localarray = NULL;
// size is a large constant> 10,000
if (localarray == NULL) localarray = new int [size];
// Algorithm goes here
}
void functionCalledLotsofTimesDynamic (int size)
{
int * localarray = NULL;
// size is a large constant> 10,000
if (localarray == NULL) localarray = new int [size];
// Algorithm goes here
delete [] localarray;
}
int _tmain (int argc, _TCHAR * argv [])
{
LARGE_INTEGER liTimeDynamic, liTimeStatic;
StartTime (& liTimeDynamic);
for (int loop = 0; loop <100000; loop ++)
{
functionCalledLotsofTimesDynamic (10000);
}
printf ("Time dynamic alocation:% lu milliseconds \ n", EndTime (& liTimeDynamic));
StartTime (& liTimeStatic);
for (int loop = 0; loop <100000; loop ++)
{
functionCalledLotsofTimesStatic (10000);
}
printf ("Time staic alocation:% lu milliseconds \ n", EndTime (& liTimeStatic));
return 0;
}
source share