0

How can I reduce execution time for this code block?

            public static IEnumerable<ListviewDataViewModel> GetModelsList<T>(this IEnumerable<T> modelsList
            , IEnumerable<ListviewColumnViewModel> modelsColumn
            , Action<ListviewDataViewModel, T> listVwItemCallback = null) where T : class
        {
            List<ListviewDataViewModel> listItms = null;

            if (modelsColumn == null || !modelsColumn.Any())
                return null;

            foreach (var d in modelsList)
            {
                var li = new ListviewDataViewModel();
                foreach (var c in modelsColumn)
                {
                    var _col = string.Empty;
                    var type = d.GetType();
                    var prp = type.GetProperty(c.ModelProperty);
                    if (prp != null)
                        _col = (prp.GetValue(d) ?? "").ToString();
                    li.ColumnItem.Add(_col);
                }

                // call the callback if available.
                listVwItemCallback?.Invoke(li, d);

                if (listItms == null)
                    listItms = new List<ListviewDataViewModel>();

                listItms.Add(li);

            }
            return listItms;
        }

When I have hundreds records in modelList, It takes about a minute to get the results. I would like to reduce the execution time to half. Can someone guide me with this?

3
  • Well the obvious way to cut the execution time is to increase the processing power of the hardware :) I don't see any opportunities in this code to improve performance much. What happens in listVwItemCallback? Commented Aug 29, 2022 at 17:59
  • @JohnWu It provides ability to perform additional action on the added list view item data. e.g. attribute setting Commented Aug 29, 2022 at 18:03
  • GetProperty() is slow, GetValue() is slow, and listVwItemCallback.Invoke() has unknown time. Can you use ExpandObject or some other technology to pull values instead of using reflection? Please expand on the use case for this and what the typical modelsList looks like. Finally, doing UI operations while processing data is slow. Better to use async for processing and update the UI separately. Commented Aug 29, 2022 at 18:21

1 Answer 1

2

Cache the result of type.GetProperty(c.ModelProperty); once for each column and stop using reflection for every single row and every single column.

And in general, you should avoid reflection altogether. There are much better ways to do this with tools ranging from T4 templates to incremental source generators.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.