For a game I am currently working on a particle system. Particles are objects with only position data. These particles have a method that update their position by using a vector field they are embedded into. The particles are inside an array
To update all particles in one physical step, I currently use a foreach:
foreach (particle p in ParList) p.update;
Where the update method is just doing two bitshifts and two additions to the original position. Now I wonder how many particles my system can handle and if I can optimize it to raise that number.
Looking into how foreach works, I found it is just a basic for loop, with doing a comparision and an addition to the index number.
I want to do what a for loop does without the check if the index number is >= 0 and without reducing the index number by one.
These two operations are not much usually, but in my case they take roughly 1/3 of the number of operations. So I wonder if I can do it this way:
switch (Parlist.Length)
{
case 1024:
ParList[1023].update;
goto case 1023;
case 1023:
ParList[1022].update;
goto case 1022;
//and so on until
case 1:
ParList[0].update;
break;
}
While it looks horrible, and I am aware this is not how it should be done, first tests make it look like I actually can rise performance quite much here. I would like to put this away into a class and access it in a more general manner like the foreach syntax is translated into a for loop. I would it to end up like this way:
eachcase (particle p in ParList)
{
//instructions using p
}
which is translated into this:
switch (Parlist.Length)
{
case 1024:
//reference to instructions using Parlist[1023]
goto case 1023;
//and so on until
case 1:
//reference to instructions using Parlist[0]
break;
}
How do I build such custom structures? Is this possible in C#?
If I am able to make this working, I also would like to implement a custom break condition like this:
eachcase (particle p in ParList, p.x == 0 && p.z == 0)
{
//instructions using p
}
which is translated into this:
switch (Parlist.Length)
{
case 1024:
if (/*break condition*/) break;
//reference to instructions using Parlist[1023]
goto case 1023;
//and so on until
case 1:
if (/*break condition*/) break;
//reference to instructions using Parlist[0]
break;
}
I read about Lambda expressions which can help me here but I am not sure how to connect it to a usual object array.