结构中的方法会对C#中的内存大小或性能产生负面影响吗



目标简介:

我目前正在尝试优化代码的性能和内存使用情况。(主要是内存瓶颈(

程序将同时具有以下元素的许多实例。尤其是当历史价格应该以最快的速度处理时。结构以最简单的方式如下:

public struct PriceElement
{
public DateTime SpotTime { get; set; }
public decimal BuyPrice { get; set; }
public decimal SellPrice { get; set; }
}

我意识到了像使用空瓶子一样使用该结构并在消费后重新填充它的性能优势。这样,我就不必为行中的每个元素重新分配内存。

然而,这也使我的代码对程序代码中的人为错误更加危险。也就是说,我想确保我总是一次更新整个结构,而不是因为忘记更新元素而只更新sellprice和buyprice。

这个元素非常简洁,但我必须将方法卸载到另一个类中的函数中,才能获得我需要的功能——这反过来会不那么直观,因此在代码中也不那么可取。

所以我添加了一些基本的方法,让我的生活变得更轻松:

public struct PriceElement
{
public PriceElement(DateTime spotTime = default(DateTime), decimal buyPrice = 0, decimal sellPrice = 0)
{
// assign datetime min value if not happened already
spotTime = spotTime == default(DateTime) ? DateTime.MinValue : spotTime;
this.SpotTime = spotTime;
this.BuyPrice = buyPrice;
this.SellPrice = sellPrice;
}
// Data
public DateTime SpotTime { get; private set; }
public decimal BuyPrice { get; private set; }
public decimal SellPrice { get; private set; }
// Methods
public decimal SpotPrice { get { return ((this.BuyPrice + this.SellPrice) / (decimal)2); } }
// refills/overwrites this price element
public void UpdatePrice(DateTime spotTime, decimal buyPrice, decimal sellPrice)
{
this.SpotTime = spotTime;
this.BuyPrice = buyPrice;
this.SellPrice = sellPrice;
}
public string ToString()
{
System.Text.StringBuilder output = new System.Text.StringBuilder();
output.Append(this.SpotTime.ToString("dd/MM/yyyy HH:mm:ss"));
output.Append(',');
output.Append(this.BuyPrice);
output.Append(',');
output.Append(this.SellPrice);
return output.ToString();
}
}

问题:

假设我有PriceElement[1000000]——这些额外的方法会给系统内存带来额外的压力吗;共享的";在PriceElement类型的所有结构之间?

这些额外的方法会分别增加创建new PriceElement(DateTime, buy, sell)实例的时间和垃圾收集器的负载吗?

会不会有任何负面影响,我在这里没有提到?

这些额外的方法会给系统内存带来额外的压力吗;共享的";在PriceElement类型的所有结构之间?

代码在所有实例之间共享。因此不会使用额外的内存。

代码与任何数据都是分开存储的,代码的内存只取决于代码的数量,而不是对象实例的数量。类和结构都是如此。主要的例外是泛型,这将为所使用的每个类型组合创建代码的副本。它有点复杂,因为代码是Jitted、缓存的等等,但在大多数情况下这是无关紧要的,因为你无论如何都无法控制它。

我建议您将结构设置为不可变的。即更改UpdatePrice,使其返回一个新结构,而不是更改现有结构。查看为什么可变结构是邪恶的详细信息。通过使结构不可变,可以将该结构标记为只读,这有助于在传递带有in参数的结构时避免复制。在现代c中,您可以引用数组中的结构,这也有助于避免复制(正如您所知(。

最新更新