【问题标题】:Performance: should method return a class or struct? [closed]性能:方法应该返回一个类还是结构? [关闭]
【发布时间】:2016-10-18 13:39:22
【问题描述】:

最近从 python 迁移到 C#。开发数学应用程序。 浏览了 SO 关于类与结构的许多问题,因此我希望有经验的人就性能提出建议。

详情

我有一个方法,在其执行过程中计算了 6 个 double 变量和大约 6 个相同长度的 double[] 数组。我希望我的方法将它们全部“打包”到一个变量中。不打算改变它们,我只需要一个存储和访问它们。在应用执行过程中,方法会被多次调用,这样的存储也会被创建多次(最多40个)。

重现示例

public (???) Method (params)
{ 
 double return_value1 = actions_with_params1;
 double return_value2 = actions_with_params2;
 double[] return_array1 = actions_with_paramsin_a_loop1;
 double[] return_array2 = actions_with_paramsin_a_loop2;
}

... 等等。我想返回一个同时包含doubles 和double[]s 的变量。我应该使用(???) 的更好的insetafd 吗?类或结构,关于性能?

谢谢!

【问题讨论】:

  • 我建议你看看this优秀的答案。
  • 老实说,在 C# 中始终使用类,除非某些要求强制您使用结构(例如与本机代码互操作),或者您运行了探查器并发现 GC Gen 0 占用了不可接受的数量时间,而 Gen 0 的缓慢是由于它被成千上万个可以用“值类型语义”处理的小型短寿命类所引起的。除了这两种特定情况,只需使用一个类。
  • 谢谢大家!因此,如果在应用程序执行期间我将创建一个由我的方法返回的 100 个对象的数组,我将面临由于堆栈被填充而导致性能下降的问题,对吗?
  • 参见this answer,但也知道并非所有结构都存在于堆栈中。

标签: c# performance class struct


【解决方案1】:

这是我如何做的一个示例:

class Program
{
    static void Main(string[] args)
    {
        List<Container> myValueStorage = new List<Container>();

        for (int i = 1; i < WhateverAmountOfOperations; i++)
        {
            myValueStorage.Add(YourMethod(yourParams));
        }
    }

    public static Container YourMethod(yourParams)
    {
        //Perform your calculations and store your results in the following variables
        double[] double_results; //An array of doubles
        double[][] double_array_results; //An array of double arrays

        //Create and return a class object containing the values
        return new Container(double_results, double_array_results);
    }


}
class Container
{
    double[] _doubles { get; }
    double[][] _double_arrays { get; }
    public Container (double[] doubles, double[][] double_arrays)
    {
        _doubles = doubles;
        _double_arrays = double_arrays;
    }
}

【讨论】:

    猜你喜欢
    • 2016-10-01
    • 2011-03-11
    • 2021-03-11
    • 2016-10-21
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多