向对象添加项目花费的时间太长

时间:2018-01-05 02:18:12

标签: c# model-view-controller

我有一个方法可以构建一个对象数组(列表)并将其返回给父对象。我在MVC应用程序中的表现非常糟糕,所以我决定添加一个秒表来捕获正在调用的代码的各个区域。我现在把它隔离到这个区域:                 var items = new List();

            _stopwatch.Start();

            var query = (from img in db.links
                         join link in db.lScc on img.pkID equals link.nLinkConfig
                         select new
                         {
                             ImageBase64 = img.bzImage,
                             ImageType = img.szImageType,
                             Description = img.szDescription,
                             URL = img.szURI,
                             HrefTarget = img.nWindowBehavior,
                             GroupName = link.szGroupName,
                             LinkConfig = link.nLinkConfig
                         }).DistinctBy(x => x.LinkConfig);
            _stopwatch.Stop();

            _stopwatch.Start();

            foreach (var item in query)
            {
                    items.Add(new
                    {
                        ImageBase64 = item.ImageBase64 != null && item.ImageBase64.Length > 0 ? Convert.ToBase64String(item.ImageBase64) : "",
                        ImageType = string.IsNullOrEmpty(item.ImageType) ? "" : item.ImageType,
                        Description = string.IsNullOrEmpty(item.Description) ? "" : item.Description,
                        URL = string.IsNullOrEmpty(item.URL) ? "" : item.URL,
                        HrefTarget = item.HrefTarget,
                        GroupName = item.GroupName
                    });
            }
            _stopwatch.Stop(); // takes around 11 seconds for this to complete about 20 iterations

我首先想到它可能是...... Convert.ToBase64String(item.ImageBase64)......但我评论说它出来了它基本上没有效果。

任何人都有什么想法可能导致缓慢?这应该只需要几分之一秒即可完成。它涉及UI,因此需要更具响应性。

2 个答案:

答案 0 :(得分:0)

问题似乎是您要将数据库中的所有项加载到查询中而不是延迟加载结果。往返db的往返速度非常慢。

        var query = (from img in db.links
                     join link in db.lScc on img.pkID equals link.nLinkConfig
                     select new
                     {
                         ImageBase64 = img.bzImage,
                         ImageType = img.szImageType,
                         Description = img.szDescription,
                         URL = img.szURI,
                         HrefTarget = img.nWindowBehavior,
                         GroupName = link.szGroupName,
                         LinkConfig = link.nLinkConfig
                     }).DistinctBy(x => x.LinkConfig);
query.count();

query.count会将所有项目一次性加载到您的集合中,而不是延迟加载您的集合

答案 1 :(得分:0)

事实证明我的数据模型有问题所以在model.edmx中设置this.Configuration.LazyLoadingEnabled = false并没有禁用延迟加载。我从数据库更新了模型并修复了问题(有一个删除的表不断回来)并重新尝试。它现在是以前的1/4。感谢您的提示!