Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When instantiating an object, does it all get stored in memory?

Tags:

c#

object

memory

Just short question, if you have a class with just one 1 property, and lots of (non static) methods, does an entirely new object get stored every time you say 'new object()', or just the property, and the methods in some 'common' memory space so the same Type can reference to that?

Thus, is having a large class always performing worse than a small class in terms of instantiation time?

like image 882
user2713516 Avatar asked Sep 11 '13 14:09

user2713516


1 Answers

Memory allocation may prove to be time consuming indeed. Still, I believe a cleaner, more obvious measurement of resource consumption would be occupied space not instantiation time.

As you have stated yourself already, it is the case that methods, static or not, occupy memory space just once. The this reference is just a hidden parameter, which gets sent from caller to called code just like any other parameter and in the end, all methods are just plain ol' functions (or routines).

In a simplistic way of putting it, so do all static fields. Don't think about properties. They are just high level wrappers for methods which in the end access fields.

Instance fields are what occupies space, per instance. But there are other things, like runtime type information which get allocated also.

In short, your assumption is correct.

EDIT

Just as a recap:

  • If by "large class" you mean a class which defines a lot of methods, then no, instantiation time will not be affected.
  • On the other hand, if by that term, you mean a class which defines a lot of instance fields, then yeah, instantiation time will be affected.

Although this is not my happy place (I know almost nothing of how good ol' malloc actually manages to defragment memory) thinking that allocating a lot of memory would take a longer time is in a strange way I can't put my finger on, like saying that

"adding the numbers 1024 and 2048 takes a bit longer than adding the numbers 3 and 4"

(given all 4 numbers are stored in variables of same numerical type).

So I would worry more about memory consumption. I'm sure time is somehow affected too, but maybe logarithmically.

like image 123
Eduard Dumitru Avatar answered Sep 21 '22 08:09

Eduard Dumitru