Original Post
I'm trying to optimize a program I'm working on. I have a function that has to do a few look ups in rather large arrays, and this function gets called a lot. So if i can shave off a few cycles here, it'll help all the way down the line. Basically heres the basic idea I would like to see if using stackalloc would speed things up, though I'm having a bit of trouble with it. And am not entirely sure the scope of an array created by stackalloc. I would like to try is something more like: So I can run it through a profiler and see which one is faster. But I have the feeling that those arrays might fall out of scope as soon as the static constructor is finished, and I would be pointing to pretty much random data. And I'm having trouble finding decent examples of people using stackalloc, most are just one or two lines of code showing the syntax. Is there something I'm missing, or am I just holding on too tight to old C/C++ ways to try to get that last little bit of performance out of this class.
public class Worker
{
private static int[] Data1 = new int[1 << 16];
private static int[] Data2 = new int[1 << 16];
static Worker()
{
//Fill Data1 and Data2
}
public static void Process(out int data1, out int data2)
{
//Calculate and return data from Data1 and Data2
}
}
unsafe public class Worker
{
static private int* pData1;
static private int* pData2;
static Worker()
{
int* tpData1 = stackalloc int[1 << 16];
pData1 = tpData1;
int tpData2 = stackalloc int[1 << 16];
pData2 = tpData2;
}
public static void Process(out int data1, out int data2)
{
//Calculate and return data
data1 = *(pData1 + i);
data2 = *(pData2 + i);
}
}