patterncsharpMinor
Quickly updating a mass of objects
Viewed 0 times
massquicklyupdatingobjects
Problem
int X = 1;
int Y = 0;
while (X != 99 - 1 || Y != 99 - 1)
{
Y++;
if (Y > 99 - 1)
{
X += 1;
Y = 1;
}
Layer1ID[X, Y].Update(X, Y);
Layer2ID[X, Y].Update(X, Y);
}This must update a total of 19602 objects each tick. Is there any way to speed this up? Threading maybe?
Objects(Ground and buildings) are stored in Layer1 and Layer2 ID Arrays of size 99x99. Most of them do nothing during the update method.
I've only recently began programming, so I apologize for the minimal information and ignorance.
Edit: Solved my own problem w/ help
if (ObjectManager._r.Next(0, 5) == 3)
{
NeedUpdate = new List();
for (int x = 1; x < Layer1ID.GetLength(0); x++)
{
for (int y = 1; y < Layer2ID.GetLength(1); y++)
{
if (Layer1ID[x, y].Updates || Layer2ID[x, y].Updates)
{
NeedUpdate.Add(new Point(x, y));
}
}
}
}
foreach (Point P in NeedUpdate)
{
Layer1ID[P.X, P.Y].Update(P.X, P.Y);
Layer2ID[P.X, P.Y].Update(P.X, P.Y);
}Solution
While not answering your question, I would like to point out problems with your loop conditions.
First, the condition
Arrays go from 0 to N-1. Let us assume that you have declared something like
You would make two nested loops
In .NET 4.0 there is a parallel for statement, however if you are updating the UI, what your
See Parallel.For Method in .NET 4.0 vs the C# For Loop.
First, the condition
X != 99 - 1 looks strange. It is the same as X 98!Arrays go from 0 to N-1. Let us assume that you have declared something like
const int N = 99;
Layer[,] layer = new Layer[N, N];You would make two nested loops
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++) {
layer[x,y].Update(x,y);
}
}In .NET 4.0 there is a parallel for statement, however if you are updating the UI, what your
Update statement suggests, then a parallel processing is of little help. Only "pure" calculations will experience an increased calculation power when using parallel processing. Also, the single tasks must have a substantial amount of work to process; otherwise the overhead associated with parallel processing will outweigh the benefits.See Parallel.For Method in .NET 4.0 vs the C# For Loop.
Code Snippets
const int N = 99;
Layer[,] layer = new Layer[N, N];for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++) {
layer[x,y].Update(x,y);
}
}Context
StackExchange Code Review Q#8899, answer score: 4
Revisions (0)
No revisions yet.