Navaneeth.K.N wrote:
"Peter Duniho" wrote:
>If you can explain why you think knowing the size of the class is useful,
it might be possible to provide an answer that more precisely meets your
needs.
There are two reasons why I am asking it. First one is purely for academic
interest. Second, I am working on a pocket PC application which has very less
memory. So my boss is asking me to find where the bottleneck is.
I know there would be many instances and calculating the class size as a
whole doesn't make any sense. But assume we have only one instance, then how
do we go about calculating the size ?
I think the simplest approach is to allocate a large number
of them and then measure how much memory usage increase and then
do a simple division.
The program attached seems to indicate that:
mem usage = 4 byte for ref + 8 byte object overhead + size of data
on my version of .NET and several unknown factors. I am sure
there are other factors that influence memory usage.
Arne
=================================================
using System;
namespace E
{
public class Sizer<Twhere T : class,new()
{
private const int N = 100000;
public static int Calc()
{
GC.Collect();
long m1 = GC.GetTotalMemory(false);
T[] a = new T[N];
for(int i = 0; i < N; i++)
{
a[i] = new T();
}
long m2 = GC.GetTotalMemory(false);
return (int)((m2 - m1) / N);
}
}
public class A
{
private int iv;
public int Iv {
get { return iv; }
set { iv = value; }
}
}
public class B
{
private int iv;
private double xv;
public int Iv
{
get { return iv; }
set { iv = value; }
}
public double Xv
{
get { return xv; }
set { xv = value; }
}
}
public class C
{
private int iv;
public int Iv {
get { return iv; }
set { iv = value; }
}
public virtual void Foo() { }
public virtual void Bar() { }
}
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine(Sizer<A>.Calc());
Console.WriteLine(Sizer<B>.Calc());
Console.WriteLine(Sizer<C>.Calc());
Console.ReadKey();
}
}
}