创建公共对象构造函数是否会影响性能

本文关键字:影响 性能 是否 公共对象 构造函数 创建 | 更新日期: 2023-09-27 18:14:33

背景

假设我有一个Address对象:

public class Address_Model{
     public int Id {get; set;}
     public string Street{get; set;}
     public string City {get; set;}
     public string State {get; set;}
     public string PostalCode{get; set;}
}

此属性用于其他几个对象(即office对象、home对象等(:

public class Office_Model{
     public int Id {get; set;}
     public Address_Model Address{get; set;}
     //. . . (other properties specific to the office model)
}
public class Home_Model{
     public int Id {get; set;}
     public Address_Model Address{get; set;}
     //. . . (other properties specific to the home model)
}

这些模特住在我的BLL里。在使用DAL数据的构造函数中,我目前手动构造Address属性:

public Office_Model GetOffice(int id){
var office = DAL.SomeClass.GettOfficeById(id);
return new Office_Model
{
   Id = office.Id,
   Address = new Address_Model{
       Id = office.Address.Id,
       Street = office.Address.Street,
       City = office.Address.City,
       State = office.Address.State,
       PostalCode = office.Address.PostalCode
   }
}
}
public Home_Model GetHome(int id){
var home = DAL.SomeClass.GettHomeById(id);
return new Home_Model
{
   Id = home.Id,
   Address = new Address_Model{
       Id = home.Address.Id,
       Street = home.Address.Street,
       City = home.Address.City,
       State = home.Address.State,
       PostalCode = home.Address.PostalCode
   }
}
}

为了提高代码的可维护性(例如,不必在构造Address_Model的所有地方添加像Street2这样的新属性(,我想创建一种构造地址模型的通用方法:

public Address_Model GetAddressModel(DAL.SomeClass.Address address){
     return new Address_Model{
           Id = address.Address.Id,
           Street = address.Address.Street,
           City = address.Address.City,
           State = address.Address.State,
           PostalCode = address.Address.PostalCode
     }
}

现在我的BLL getter方法看起来更像这样:

  public Office_Model GetOffice(int id){
    var office = DAL.SomeClass.GettOfficeById(id);
    return new Office_Model
    {
       Id = office.Id,
       Address = GetAddressModel(office.Address);
    }
    }
    public Home_Model GetHome(int id){
    var home = DAL.SomeClass.GettHomeById(id);
    return new Home_Model
    {
       Id = home.Id,
       Address = GetAddressModel(home.Address);
    }
    }

问题

委托该施工作业会对绩效产生负面影响吗?我是性能评测的新手,刚刚了解了boxingunboxing;我不确定这种类型的性能下降是否适用于我在这里所做的工作。

显然,我已经在很大程度上简化了这个例子。事实上,还有更多的嵌套对象需要构建。

创建公共对象构造函数是否会影响性能

Boxing,来自MSDN:

装箱是将值类型转换为类型对象或到由该值类型实现的任何接口类型。

由于Address对象是一个引用类型(标记为class而不是struct(,并且您希望接收一个Address类型作为参数,因此代码中不会出现装箱。更重要的是,JIT编译器可能会决定内联您的方法调用,这将消除为该调用一起创建新的堆栈帧。