1

Let's assume that I have a class named Foo. The class has no state of its own but has a ton of functions.

class Foo
{
  public void One()
  {
    // 500 lines of code
    var bigObject = new BigBigBigObject();

    // do something to the big object

    // launch long-running operation

    // do some COM interop
  }

  public Result Two()
  {
    // 2800 lines
    using(var disposable = new SomeCustomDisposable())
    {
      ...
    }
  }

  public async Task<Bar> FourteenHundredAndFifty()
  {
    ...
  }
}

And in the main method, we have a reference to Foo like so:

public class Program
{
  public static void Main(string[] args)
  {
    var foo = new Foo();

    // run the program for a long time
    // calling functions on Foo

    ....
  }
}

My question is: even though a reference to Foo is kept alive throughout the life of the program, since Foo doesn't have state of its own, what impact does it have on the memory footprint of the application?

I would assume that since it has no state, its size would still be 12 bytes (on a 32-bit machine and 24 bytes on a 64-bit machine) on the GC heap.

However:

  1. It might have a lot of bytes occupied on the loader heap since it has many methods and so their method definitions will be occupying a considerable amount of memory.

  2. Even though it has no state of its own, when one or more of its functions are called, they leave large objects on the large object heap. Even then, what those methods do to the GC heap and whether or not they leave large objects for a long time and whether or not they cause too many allocations or GC's are all dependent on the code in those functions. The size of Foo is still small and the fact that the reference to Foo is kept alive throughout the program has no bearing on the GC heap.

Are my assumptions correct?

Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336

1 Answers1

1

Your class will not grow larger in memory from adding methods if that is your concern. Only fields and properties will increase the in-memory size of your class. The class instance in memory contains a pointer to a larger common structure that contains method pointers and class meta data.

You are correct in assuming the minimum class size for x86 and x64 are 12 and 24 bytes respectively. See this post for more details.

Slight
  • 1,541
  • 3
  • 19
  • 38