1

I have a program in VB.net that uses a 3D array:

Private gridList(10, 900, 900) As GridElement

Now, I just used a Memory Profiler on it (because my application is having some major leak issues or something) and apparently, this array (containing at the moment of testing 0-30 elements at one time) is using 94% of the memory currently in use by my application. Even when it is empty it takes up huge amounts of memory.

My only assumption is that even empty arrays take up space! This puts a major blow into my plans!

My Question:

Is there any alternative to this that allows me to still have the same abilities to map i.g. I've been using it like this:

Dim cGE as GridElement = gridList(3, 5, 7)

but doesn't hog up so much memory for things that aren't using memory?

Thanks!

Freesnöw
  • 30,619
  • 30
  • 89
  • 138
  • 1
    "even empty arrays take up space!" - var x=new double[10] will take 80 bytes whether you assign any of them to a value or not, because the system reserves space to it. Isn't it? – Andr Sep 28 '11 at 14:02

1 Answers1

1

Do Arrays take up space even without values in them in .net?

No. But your array has values in it. And hence takes up space.

To avoid keeping a lot of elements in memory when you only access a few of all the possible elements, you need to use a so-called sparse array. In .NET, this is easiest implemented via a Dictionary, where the key in your case would be a three-element structure*, and the value would be a GridElement.


* If you’re using an up-to-date version of .NET, then you can model this via a Tuple(Of Integer, Integer, Integer)

Community
  • 1
  • 1
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    To elaborate: non-null arrays *always* have values in them. – LukeH Sep 28 '11 at 14:00
  • Well, these are very small elements that I have in there. Adding just one element adds a total of 35MB to the total used memory being held by the 3D array. – Freesnöw Sep 28 '11 at 14:01
  • So even if every spot in my array is set as `nothing` it still has stuff in it? – Freesnöw Sep 28 '11 at 14:02
  • 1
    @Dade Yes, it has 10 * 900 * 900 times `Nothing` in it. Which accounts for [around 31 MiB](http://www.google.com/search?hl=en&q=10+%2A+900+%2A+900+%2A+4+bytes+in+megabyte) assuming that a reference takes up four bytes (it’s twice as much on some machines). – Konrad Rudolph Sep 28 '11 at 14:04
  • Well, I'm focusing my project towards the .net Framework 3.5 because a lot of computers don't have the 4.0. Tuple is not in 3.5. – Freesnöw Sep 28 '11 at 14:12
  • Alright, I'll just use this implantation shown here: http://stackoverflow.com/questions/152019/will-a-future-version-of-net-support-tuples-in-c – Freesnöw Sep 28 '11 at 14:28