I currently have a program that intercepts some packets, does some modification/adding classes to lists based on the information and sends it on.
What I am currently doing is when I add an item I lock the list I’m adding to whilst I add it. However I have a PictureBox which draws information from the lists every 50ms or so. Currently the way I do it looks something like this:
Graphics g = e.Graphics;
lock (Core.Collections.SpaceStations)
{
foreach (Classes.Station station in Core.Collections.SpaceStations)
{
Image img;
switch (station.Company)
{
case 1:
img = Prog.Properties.Resources.mmo_station;
break;
case 2:
img = Prog.Properties.Resources.eic_station;
break;
case 3:
img = Prog.Properties.Resources.vru_station;
break;
default:
img = new Bitmap(50, 50);
break;
}
g.DrawImage(img, (float)((station.Position.x - 750) / Core.CurrentMap.ByX), (float)((station.Position.y - 750) / Core.CurrentMap.ByY), 35, 35);
}
}
As you can see, it locks for the entire length of the iteration which causes my packet handler to block until it finishes painting and can cause lag for both the server and client (because I lock before adding or removing items in the packet handler). My question is would it be quicker to copy all the items from the List into a temporary list inside the lock and then draw them all outside the lock from the temp list? Mainly my question is, is it faster to iterate through a list or to copy a list.
I think copying the list is better option here.
It will defiantly improve the performance but would be memory intensive, which can be handled to an extend by properly disposing the list after drawing.