0

I have a 2d array:

int[,] array = new int[m, n];

I'm trying to initialize all the values in the array to Int32.MaxValue in the most performant way possible. The simple solution is to do a double-for-loop, but I don't think that's the most performant and my internet searches have failed to turn up anything.

Does someone out there know a more efficient way to do this?

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
teuber789
  • 1,527
  • 16
  • 28
  • 2
    ***in the most performant way possible*** On which platform? Which bitness? Which implementation of the .NET framework? Have you benchmarked anything? – Frédéric Hamidi Mar 14 '16 at 21:46
  • Just access each array element by index. Bang. `O(1)`. (Tongue is a little in my cheek, here). – TEK Mar 14 '16 at 21:47
  • 1
    You want to set m x n values. How would something be faster than a double for-loop that does *exactly* that? – Dennis_E Mar 14 '16 at 21:48
  • The platform is .NET 4. I'm not sure what you mean by "bitness", but i'm only using Int32 if that's what you mean. – teuber789 Mar 14 '16 at 21:51
  • 1
    Have you benchmarked your code and determined that array initialization is a performance bottleneck? There aren't any lowlevel hacks you can do around this in .NET. You need to access each element in order to set its value. The double for-loop is the fastest way. Either that, or change the meaning of your data so that `0` has the meaning you were going to assign to `Int32.MaxValue`. – Blorgbeard Mar 14 '16 at 21:52
  • Actually, this [question](http://stackoverflow.com/questions/5943850/fastest-way-to-fill-an-array-with-a-single-value)'s answers have some ideas to try which may be faster, but you'll have to adapt them to a 2d array (or switch to using a 1d array + math when you index it) – Blorgbeard Mar 14 '16 at 21:56
  • In one view, this is legit question. In another view... what, you don't know the answer? - You can't access all cells of the multi-dim. the array at the same time unless you do some multi-threading, where each thread will populate part of your n-count. But how much time you gonna win? Remember that to spin-out a thread also takes time – T.S. Mar 14 '16 at 22:55
  • @Blorgbeard I have benchmarked the code and having a double for-loop does make a significant impact on code run time...enough that my test runs go from taking only ~3.5 seconds to ~53 seconds! And unfortunately, since I'm implementing a DNA sequence mutation scoring algorithm, changing the meaning of Int32.Max and 0 isn't exactly an option :/ – teuber789 Mar 15 '16 at 05:04
  • I'm also afraid that doing a 1d array with math for the indices wouldn't save on the time required to initialize all the array values to Int32.Max - you'd still have to initialize the same number of elements one at a time. – teuber789 Mar 15 '16 at 05:08
  • Did you read the answers to the question I linked above? – Blorgbeard Mar 15 '16 at 06:47

0 Answers0