improve performance of recursive function in c# method 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 =&gt; 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);
         }
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&lt;string,PropertyInfo[]&gt; typeProperties = new Dictionary&lt;string,PropertyInfo[]&gt;();

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).