views:

79

answers:

4

I have the next class which instantiated about 40 million times and all its instances take about 80% of all process memory (more than 15GB).

class MyClass
{
    String Field1
    String Field2
    String Field3
    int Field4
    int Field5
    float Field6
    SomeEnum Field7
    Boolean Field8
    Boolean Field9
    Boolean Field10
    Byte Field11
    Byte Field12
}

I want somehow to optimize this class, but not sure what can I do in this case. I thought about to combine boolean field to a single byte or customize fields alignment, but not sure if it worse and if it will not break something. Also tried to change it to be a structure, but got performance problems in existing code without significant improvement.

So, what can be done here to decrease memory usage without serious performance degradation?

This code will run mostly on x64 server, x32 only in development.

EDIT:

This is service that supposed very fast return a result that depends on all this data. Very fast here is about 20ms-150ms. So all data is hashed and sorted, and every field in this class is used almost in every request to the service. May be something here designed bad, but design is not an issue here, and I just can't redesign it right now from scratch.

+1  A: 

Simple answer: do not use a class at all.

instantiated about 40 million times and all its instances take about 80% of all process memory (more than 15GB).

What for? Sounds like you need a database. Any particular reason?

TomTom
+5  A: 

Sure you could make all booleans into one field. Also combining the enum and byte values into one field could save you memory because fields are normally aligned and therefore take up more space. In .NET there are also attributes to control member alignment.

But at the end you have a design problem. Better try to redesign your application. Are all data values really needed at the same time into memory? Could you put unneeded parts to harddisk and only retrieve it if really needed?

Tell us more about what the application does so we can create some ideas for you.

codymanix
+1  A: 

Feels like a strange design, and if I'm not miscalculating, 15GB / 40 million is over 400. So assuming it's just this class taking up most of the space, that seems to indicate that each instance uses hundreds of bytes. I doubt that it would get much better by saving a few bytes by changing 3 bools to a byte.

I'm assuming it's the strings that take up most of the space, maybe you could leave the strings in the database and only store an ID in your class and then you could look them up as needed?

ho1
+1  A: 

As strings are most likely to hold the largest amount of memory you could try string interning.

Giorgi