I'm trying to write a function which will cache objects in memory.
The function below works, but performance is unbearable. What would you recommend to improve performance?
public void SerializeInsertCache(object item)
{
//Get type of item object item
Type type = item.GetType();
//Get all of attributes type of item object
TypeAttributes attributesType = type.Attributes;
//Get object type full name for cach key
string rootName = type.Name;
string name = type.Name;
PropertyInfo[] properties = type.GetProperties();
PropertyInfo idRoot = properties.Where(p => p.Name == "Id").SingleOrDefault();
int rootId = (int)idRoot.GetValue(item);
string rootKey = "";
foreach (var property in properties)
{
string propertyName = property.Name;
var propertyValue = property.GetValue(item);
Type propertyType = property.PropertyType;
string propertyTypeName = propertyType.Name;
bool cacheStatus = true;
SerializeInsertCache(property);//recursive function
}
SaveInCache(item);
}
1 Answer 1
Vast swaths of this code have no apparent use. Cutting out the code that does not appear to have an effect, you seem to be left with:
public void SerializeInsertCache(object item)
{
Type type = item.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (var property in properties)
{
SerializeInsertCache(property);
}
SaveInCache(item);
}
Ben Voigt's point about not repeating reflection might look something like this:
private Dictionary<string,PropertyInfo[]> typeProperties = new Dictionary<string,PropertyInfo[]>();
public void SerializeInsertCache(object item)
{
Type type = item.GetType();
string name = type.Name;
PropertyInfo[] properties;
if (!typeProperties.TryGetValue(name, out properties))
{
properties = type.GetProperties();
typeProperties.Add(name,properties);
}
foreach (var property in properties)
{
SerializeInsertCache(property,typeProperties);
}
SaveInCache(item);
}
However, that said, I also think this is overcomplicating the problem. Why are you wanting to serialize these things in the first place? If they're being kept in memory, there is almost certainly a better approach (which we can't suggest until we know more about what problem you're solving).
propertyName
,propertyValue
,propertyType
,propertyTypeName
&cacheStatus
are assigned to but never used; get rid of them and you'll get some performance gain. \$\endgroup\$Dictionary<string, object>()
, and retrieve with a(ExpectedType)cache.Get("key_name")
. I may be way off the mark though which is why this is a comment. \$\endgroup\$item
in to theSaveInCache
method, and discard everything you reflected. \$\endgroup\$