Pratyush Dhanuka
Pratyush Dhanuka

Reputation: 1445

Passing a complex data vs passing its property

I know this is a basic question but I kind of wanted to know some key details in their differences and how does it affects performance !

Below is a C# example.

Suppose I have a Person class with properties like

public class Person 
{
    int PersonIds{get;set;}
    string Name{get;set;}
    ...
    ... 
}

and I have defined somewhere

List<Person> myFamily; // I later initialize to contail all my family members.

Now I have 2 functions fun1 and fun2

List<Person> fun1(List<Person> myFamily)
 {
    ... // here some logic occurs and I get some less no. of Person in return list.
    ...
 }

somewhere else

List<Person> selectedPersons = fun1(myFamily);

VS

 List<int> fun2(List<int> myFamilyPersonIds)
 {
    ... // Here same logic occurs as fun1 but it only needs personID to perform it.
    ...
 }

somewhere else

 List<int> selectedPersonIds = fun2(myFamilyPersonIds);
 List<Person> selectedPersons = myFamily.where(a=>selectedPersonIds.contains(a.PersonId));

I want to know in what ways does this effect the performance.

Tips and suggestions are also welcome.

Upvotes: 0

Views: 42

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415820

The only way to know the correct answer is to use a tool to profile the code, and see where your program is really spending it's time. Before this, you're just doing guess-work and pre-mature optimization.

However, assuming you already have these objects constructed, I tend to prefer the fun1() option. This is because it's passing around references to the same objects in memory. The fun2() option needs to make copies of the integer IDs. As a reference is the same size as an integer, I'd expect copying integers to be about the same amount of work as copying references. That part is a wash.

However, by staying with references you can save the later step of finding the whole object based on the ID. That should simplify your code, making it easier to read and maintain, and save work for the computer (improve performance), too.

Also, imagine for a moment that your property were something larger than an integer... say, a string. In this case, passing the object could be a huge performance win. But again, what I expect is just a naive guess without results from a real profiling tool.

Upvotes: 2

Related Questions