mardi 18 avril 2023

Performance impact of reflection when creating the Json object

I have below code to prepare the logEventInfo object to log the data. I am using the Nlog. I found it is convenient to use reflection to add the name and value dynamically. But I know there is a big performance impact.

public static LogEventInfo ToLogEventInfo(this ILogItem data, string message, Exception ex = null)
        {
            var eventInfo = new LogEventInfo();

            if (ex != null)
                eventInfo.Exception = ex;

            if (data != null)
            {
                data.EventMessage = message;
                data.LogTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Utc);
                data.LogId = Guid.NewGuid();

                var properties = data.GetType().GetProperties();
                foreach (PropertyInfo property in properties) //Possibly a performance impact.
                {
                    eventInfo.Properties[property.Name] = property.GetValue(data, null);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(message))
                    eventInfo.Message = message;
            }

            return eventInfo;
        }

This ToLogEvenInfo function will be called in a loop. The data will be looped may be millions. Is there a better way to implement the below function? Thanks a lot.





Aucun commentaire:

Enregistrer un commentaire