I have two complex objects of the same type. I want to check if there is any difference between the two of these objects. I have two options of achieving this, either by converting both of these objects to string using JsonConvert.SerializeObject and compare the string like
var existingData = JsonConvert.SerializeObject(objOld);
var newData = JsonConvert.SerializeObject(objNew);
return existingData == newData;
The other option is to use the reflection and loop through all the properties like below.
protected bool MatchObject(object newObj, object oldObj)
{
Type currentType = newObj.GetType();
PropertyInfo[] props = currentType.GetProperties();
bool isSameObject = true;
foreach (var prop in props)
{
var i = prop.GetValue(newObj);
var f = prop.GetValue(oldObj);
if (!object.Equals(i, f))
{
isSameObject = false;
break;
}
}
return isSameObject;
}
Which of the above approach is more efficient as per the performance perspective?