Object id or Object reference

.net c# dapper oop

Question

I am wondering if is it better to add a reference to an external object in my class or to add just its Id. I want to create those objects from database, using dapper or directly ADO.NET. So I want to know if there is a performance difference between the two approach.

for example I have the following object

Class Object1
{
    int Id {get;set;}
    string Name {get;set;}
    //... etc
}

and I have another object Object2 which have a reference to Object1

Class Object2
{
    int Id {get;set;}
    //is it better to add this
    Object1 object1 {get;set;}
    //or to add just an Id
    int objectId {get;set;}
}

Object2 may have other references to other objects

Accepted Answer

I would stick with a reference to the object, as it will reduce the amount of access code you have to write when using your object relational mapper. Like retrieving the object from the ID, as well as reducing the likely hood of making unnecessary repeat accesses.

However if you are storing a very large amount of these objects in memory and you don't always require access to the object reference, it may be more efficient to just keep the ID.

It's kind of a balancing act but in most cases object reference won't affect you. I would need more information on the use case.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why