views:

82

answers:

2

Good morning SO,

I have a class that contains the following static array:

public static ResultObject[] ResultArray = new ResultObject[500];

In my program, there are 12million instances of this class that all add to this array. I'm getting a OutOfMemoryException and think this might be the reason why.

Is there any way I can manage the memory being used by this array better so I won't get this exception? If not, which is faster, writing to a file or database?

I'd prefer to hold this data in memory, but if that is the cause of my problem, then I'll have to try something else.

Thanks!

A: 

This might not be a direct answer to your question but dont you think it might be possible that the 12 million instances of the class containing the static array and not the array itself may be causing this memory problem?

The first thing I would do before trying to optimize is to absolutely ascertain the cause of the issues.

Use a memory profiler and ascertain the cause of your memory problem before you figure out exactly how to optimize it. You will be surprised at times when you investigate to find that the real cause might not be always what you expect.

You can use the CLR profiler or a trial version of commercial profiler like ANTS (atleast for a start).

InSane
I agree, but I also think we could solve this one by static analysis
uosɐſ
A: 

If ResultObject is static, then you should only have one instance of it, even if you have millions of instances of the class. As others have suggested, double-check that the memory problem isn't being caused by something else in your class.

If you're certain the memory problem is related to ResultObject, check carefully to see what you're doing with this class. For example are you doing anything that might result in a copy of ResultObject being made, for each of those 12 million instances?

NeilDurant
@Neil, there's a loop that goes through 500 timesteps (each ResultObject contains sums for each timestep). At the beginning of the loop that goes through each timestep, it checks to see if ResultArray[timestep] is null, if so, it sets it to new ResultObject(). That shouldn't cause it to create many many instances of ResultObject, right? I could definitely be wrong...
Soo
Sounds like that will create 500 instances of ResultObject. Can you post your ResultObject source?
asawyer
ResultObject just contains some doubles that are used for summing purposes.
Soo
Do you get better results switching ResultObject from a Class to a Struct?
asawyer