Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a big existing object or create and pass a small object

Tags:

c#

Suppose I have a big object that contains the properties I require and additionally several methods and a few sizeable collections.

I would like to know what would cost more: To pass as an argument this big object that already exists, or create a small object containing only the handful of properties I require and pass that?

like image 714
Steve Avatar asked Jul 11 '12 03:07

Steve


2 Answers

If you're just passing it as an argument to a method, passing the "big" object is "cheaper" - you'll only be passing a copy of the object reference, which is just the size of a pointer (unless the object is of a struct type, in which case the whole "object" is copied into the stack). If you were to create a new object, even if it's small, you'd be paying the price of the allocation and copying of the properties onto it, which you don't have if you pass the "large" object.

If you're passing it in a way that it needs to be serialized (i.e., across applications, in a call to a web service, etc.), then having the smaller object (essentially a DTO, Data Transfer Object) is preferred.

like image 125
carlosfigueira Avatar answered Oct 21 '22 00:10

carlosfigueira


As long as you pass by reference it doesn't matter. Therefore you shouldn't introduce additional complexity. In fact, it would cost the machine more, since it then would have to create that container object as well.

Since you seem concerned with performance I'd recommend to learn how pointers and memory management works in C. Once you understand that, you will have a much easier time understanding how their abstracted versions in higher level languages impact performance.

like image 27
Michel Müller Avatar answered Oct 21 '22 00:10

Michel Müller