首页 > 解决方案 > int 和 long 重载的性能损失

问题描述

问题:

当实体中的直接数据访问需要 0.4 秒时,为什么将列表从受保护的内部类传递到 API 方法然后返回我的 UI 需要 4 秒?是因为通过这些方法实际传递了列表吗?

背景:

我希望创建一个“API”层,它位于使用实体框架的数据访问层和我的 UI 层之间。这个想法是限制对 CRUD 操作的访问并通过 API 强制执行所有操作,但是我注意到性能很糟糕。

当我在这里使用我的类结构时,这种情况下的 get 方法需要4 秒才能运行:

public class API
{
    DataAccessClass _dataAccess = new DataAccessClass();

    public List<Items> GetById(int id)
    {
        return _dataAccess.Get(id);
    }

    protected internal class DataAccessClass
    {
        protected internal List<Items> GET(int id)
        { 
            using (var context = dbcontext)
            {
                return context.GetItems();
            }
        }
        protected internal List<Items> GET(long id)
        { 
            using (var context = dbcontext)
            {
                return context.GetItems();
            }
        }
    }
}

但是,当我直接在代码中使用我的 dbcontext 时(我想阻止),它使用上面受保护类中的相同代码在0.4 秒内运行:

using (var context = dbcontext)
{
     return context.GetItems();
}

编辑:

当我排除作为受保护内部部分的 API 的数据访问部分,并直接在 API 中运行 using 语句(仅删除受保护的内部部分)时,我得到了可接受的 0.4 秒。

标签: c#.netperformanceentity-frameworkentity

解决方案


为了解决我的性能问题,我从上面的 GET 类中删除了重载。

通过更改我的两个 get 方法(一个需要 int 和一个 long)的方法名称来解决原始问题中的性能问题。不知道为什么这些重载会导致问题,但通过删除重载并直接指定名称,我的性能问题得到了解决。

我的工人阶级看起来像:

public class API
{
    DataAccessClass _dataAccess = new DataAccessClass();

    public List<Items> GetById(int id)
    {
        return _dataAccess.Get(id);
    }

    protected internal class DataAccessClass
    {
        protected internal List<Items> GetByInt(int id)
        { 
            using (var context = dbcontext)
            {
                return context.GetItems();
            }
        }
        protected internal List<Items> GetByLong(long id)
        { 
            using (var context = dbcontext)
            {
                return context.GetItems();
            }
        }
    }
}

推荐阅读