Misconceptions with Member functions

I have been answering MS community postings recently and while checking the web my understanding of the ref keyword was correct in terms in terms of referencing the stack, I found a number of web sites giving false information about a related point. This annoyed me so I though I would correct it here.
Member function definitions are not held in memory allocated to object instances and are not duplicated in memory for each instance of a object you create.
Member functions are held in the class definition in memory in the space place as static methods. There is no heap memory saving by making functions static rather than instance.
Instance methods are largely the same as static methods bar a couple of small differences.
  1. They are marked in the metadata as instance
  2. They have an implicit first parameter which is the instance of the object they are running for. This is why in the IL, any intance member access is preceeded by  ldarg.0  it loads the instance to the top of the computation stack.
  3. Methods are not serialized with instances as they are not instance data. Therefore there is no space saving at all by making them static.
  4. Instance members can be virtual and therefore not open some of the optimizations that can be applied to static methods.

Just though I’d clear that up. I know there may be other differences I haven’t mentioned but the main point is made. 

This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to Misconceptions with Member functions

  1. Adam says:

    Great point – maybe the people making these assertions were getting confused with JavaScript "objects" implemented using closures which do use memory for member functions in each object instance.
    That\’s one of the reason MS switched to using the prototype method of JavaScript objects in ASP.Net Ajax Beta 2. Unfortunatley, all our code is using closures and we have to port to Beta 2 😦
    Nice blog entry on OO Javascript and ASP.Net Ajax – http://www.manuelabadia.com/blog/PermaLink,guid,c59facc0-301e-4e30-898d-428038828dcd.aspx

  2. Ciaran says:

    Good point and good post on Ajax. Thanks for the comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s