0

Let's say i have a fairly large 2D array (a bit over 2 million entries) containing some basic objects (in my case, it's a 2d array of pixel objects).

My goal is to loop through every item in the 2D array and do some basic modification to the object, such as changing one of its properties or something.

Currently i am just looping through it with a foreach and accessing each object via the loop.

This takes around 2 seconds to accomplish with C#.

I am wondering if there is a faster way for me to accomplish this. I wrote some similar code in c++ a long time ago and it performed almost instantaneously, so i'm a bit disappointed that performance has suffered a bit in C#.

Can i somehow speed things up with asynchronous code perhaps? Am i doing something in a less-than-optimal way?

foreach (Pixel p in my2Darray.Pixels) //this is a 2d array but we can still just loop through it with a single for loop
{
    p.SetColor(Color.red);
}
nuk
  • 39
  • 6
  • How much memory is the array taking? What type of machine? My concerns are with swap space. If the object exceed the available memory the data is swapped into cache which is very slow. Also if you are accessing the object with a foreach it indicates you added the object into a list and I know nothing about the list object. Then if code is being run on an Android with very little memory it would behave much different than a desktop loaded with memory. So this seems more like a trick question without providing more details of the machine and more code. – jdweng Aug 26 '19 at 23:45
  • Is `Pixel` a GDI+ `BitmapData` pixel? Calling `SetColor` on that is going to be slow. Investigate [Create Bitmap from byte array](https://stackoverflow.com/questions/6782489/). – Dour High Arch Aug 26 '19 at 23:47
  • 2
    What are the objects here? what are you doing to them, the foreach isn't the slow part here. its everything else. – TheGeneral Aug 26 '19 at 23:47
  • 1
    Without more information on the specifics of the objects, collections, and methods involved this question is too broad, no-one can help you – TheGeneral Aug 27 '19 at 00:10
  • Nested `for` may be a bit faster (or slower :) ) than `foreach` but as @TheGeneral said there is no way to actually help without more information. (Basic test shows that both options take about the same time for 1000x2000 array at 10ms just to sum integer properties of an object at all indexes confirming that its the rest of the code you did not show is the problem) – Alexei Levenkov Aug 27 '19 at 01:21
  • Sorry for the lack of detail. I am running this code on PC, 16gb ram, i7 7700 cpu. The `Pixel` object is a custom class i made. It has 3 properties - Color, X and Y. It's a very simple class. Calling SetColor should not be an expensive thing in and of itself, i can't see that being the cause of the slowness. – nuk Aug 27 '19 at 17:39

0 Answers0