【问题标题】:Performance of class with short circuit getters vs lazy getters短路吸气剂与惰性吸气剂的类性能
【发布时间】:2018-04-05 02:55:52
【问题描述】:

所以我有一个数学类,它对许多属性的 getter 执行计算。现在我转换了这些属性,以便在他们的第一次评估之后只返回那个结果。

现在关于性能,我想知道,考虑到这些实例很可能有数百甚至数千个存储在集合中,平均而言哪种方法最好?

让我担心的是后一种方法:

增加了 GC 负载,并且还影响了引用的局部性,因为 nullables 将分配内存远离父对象。

public class SomeMathType
{
     // these are structs
     public Vector A { get; }
     public Vector B { get; }
     ...
     public double Length => A + B;
     ...
}

对比

 public class SomeMathType
 {
      ...
     private double? _length;
     private Vector? _vector;

     // these are structs
     public Vector A { get; }
     public Vector B { get; }

     public Vector Vector
     {
         get
         {
             _vector = _vector ?? B - A;
             return _vector.Value;
         }
     }

     public double Length
     {
         get
         {
             _length = _length ?? Vector.Length;
             return _length.Value;
         }
     }
      ...
 }

【问题讨论】:

  • 天真的性能分析不会建立任何东西。这是一个复杂的指标,因为它取决于访问这些属性的频率与我列出的问题的成本……但是,是的,也许差异并不相关,最好使用更具可读性的选项。我只是想知道其他人对此有什么看法......
  • 我看不出Nullable<TStruct> 会如何导致装箱,除了 single 空值。
  • since it now boxes the structs into nullable reference types,但Nullable 是结构本身,而不是引用类型。
  • 编写代码是为了可读性,而不是为了性能。好的代码尽可能清楚地传达它实现的算法。为变量、属性、成员和方法使用有意义的名称。如果您遇到性能问题,请对其进行分析,找到瓶颈并加以解决。

标签: c# .net performance properties nullable


【解决方案1】:

因此,普遍的共识似乎是倾向于可读性而不是(过早地)性能优化的代码。所以我保留了最初编写的代码,至少现在是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多