开发者

C# optimization for large number of a class instances

My work uses a great number of a class ins开发者_如何学JAVAtances.

For a memory optimization, I would like to know if the using of static method will be better than simple functions.

Thanks for any suggestion around the optimization of managing lots of objects.


There is no difference between

public class Foo
{
     public Bar bar;
     public Bar baz;

     public bool Qux()
     {
         return this.bar != null;
     }
}

and

public class Foo
{
     public Bar bar;
     public Bar baz;

     public static bool Qux(Foo foo)
     {
         return foo.bar != null;
     }
}

in terms of memory consumption by a single instance. Methods consume memory per class, not per instance.

If course, you can save memory by not creating instances. So, if your static method makes instances unnecessary, go for static methods.


As a general rule: the code of your methods is shared between instances - it's not like every instance gets it's own copy of the methods. You might want to have a look at how to manage instance data, though - the flyweight pattern comes to my mind here.


Hurting your readability or changing your logic for performance issues is recommended only after you are completely sure whatever you plan to do would significantly help. This is not the case here because your solution will not really help from the first place, let alone "significantly". so the answer to your question is "no".


Does the class store any instance data or use any instance data for execution of the method? Then a static method won't work.

If the method doesn't utilize any of the instance data of the class, then making the method static would work.

If you can't make the method(s) static that you're interested in, you might consider implementing a pool for your objects.

When you need an instance, you get an available one from the pool, use it, and then return it to the pool when you're done with it. That way you don't have to create as many instances (but this assumes, of course, that you're creating many instances that don't get used often).


Making your methods static or not should not make much of a difference to the footprint of your class. If you end up instantiating your classes merely to call a member method, static might make a little difference.

If memory consumption because of many instances is a problem, you might want to have a look at the Flyweight pattern


Others' input is good. I would only add that if instances are being created and destroyed at a high rate, you will be losing a lot of time in memory management. You can rectify that by keeping pools of used objects, and re-use them without going to the memory allocator.


Methods always attached to classes, not instances. The size of the instance in the memory does not depend on method count. Therefore, using static or instance variable is not related to the memory optimization at all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜