1

It may be a stupid question but in C#, performance wise, an object's size or complexity does matter when you access one of its members through a reference? Or only that specific member is all that matters?

I know it's premature optimization but I'm curious.

1
  • 1
    Can you take specific example of scenario you have in mind.. As stated, it seems very broad question to me. Dec 22, 2014 at 6:11

1 Answer 1

7

Short answer: no.

Long answer: I assume when you write "size" of an object, you mean size (in bytes) of the member variables, and when you write "complexity", you mean number of members, number of different types used, and so on. Access to an object through a member function will result in IL code which contains

  • pushing the parameters of the method to the stack
  • pushing a "this" reference to the stack
  • calling the function (which will result in a simple call statement at the machine code level, not depending on the object's size)

(This is a simplified model, not taking things like inlining into account, but it is sufficient for answering your question). So as you see, in none of these operations the object size itself has an influence. And neither the number and structure of other member functions.

The size only matters from a performance perspective when you copy objects around, when you store them to disk or a database, or when you are accessing the data of so many different objects that your CPU cache is not sufficiently large to hold all the data accessed. The latter might happen when the "number of objects x size of object" exceeds a certain limit, but it depends also on what other things your program does, which other data is involved. So is an accumulated effect, and I doubt it counts as "performance impact caused by access to one of its members through a reference".

2
  • Thanks. So storing a collection of references into an array, it wouldn't still affect performance to access the member through the array reference to the object but it'll need to use more memory the bigger it is in order to hold these references in the array? Dec 22, 2014 at 6:20
  • @CTCCoco; when you create n objects of equal size, you will need (roughly) at least n * "size of one object" bytes in memory (isn't that obviuous?). And this is independent from the container you are using of for the object references, could be an array, a list, n individual variables, whatsoever. The container itself will need some additional space (at least n * "size of a reference"), but the size of a reference is fixed, it has nothing to do with the size of the object.
    – Doc Brown
    Dec 22, 2014 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.