When you instantiate an object, is all this stored in memory?

Just a short question, if you have a class with one single property and many (non-stationary) methods, each new object will be stored every time you say “new object ()” or just a property, and methods in some “common” memory space so the same type can refer to this?

So has a large class that always performs worse than a small class in terms of runtime?

+8
object c # memory
source share
4 answers

Memory allocation can be time consuming. However, I believe that a cleaner, more obvious measurement of resource consumption will take up space, not creation time.

As you have already stated about yourself, this is the case when methods, static or not, take up memory space only once. The this link is just a hidden parameter that is sent from the caller to the called code in the same way as any other parameter, and in the end all methods are just simple functions (or routines).

In a simplified way to set it, as well as all static fields. Do not think about the properties. These are just high-level wrappers for methods that are at the end of an access field.

Instance fields take up space per instance. But there are other things, such as runtime information, which also stands out.

In short, your assumption is correct.

EDIT

As well as a summary:

  • If by “large class” you mean a class that defines many methods, then no, the instantiation time will not be affected.
  • On the other hand, if by this term you mean a class that defines many fields of an instance, then yes, the creation time will be affected.

Although this is not my happy place (I know almost nothing about how good ol ' malloc really manages to defragment memory), thinking that allocating a large amount of memory will take longer, strange, I can’t push my finger, as if to say that

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

(provided that all 4 numbers are stored in variables of the same number type).

So, I'm more worried about memory consumption. I am sure that time is also affected, but it can be logarithmic.

+2
source share

The methods are shared. All things being equal, creating an instance of a class with many methods has almost the same cost as creating an instance with several. These are non-static fields and the amount of work performed by the designer (and some other minor factors) that determine the cost of creation.

+3
source share

Instance fields are the only thing stored in the object itself. Methods are stored in a type, which means that they exist in only one place.

In fact, instance methods are just syntactic sugar (at the IL level) for static methods that take an instance as a parameter.

+2
source share

I think you will find the information you need (and probably more) here . The code for the instance methods will be shared.

0
source share

All Articles