Mikhail T. Mikhail T. - 10 months ago 61
C# Question

Performance: should method return a class or struct?

Recently moved from python to C#. Developing math app.
Looked through many questions at SO about class vs struct, so I would like an advice from experienced people regarding performance.


I have a method, and during its execution 6 double variables are calculated and about 6 double[] arrays of same lenght. I want my method to return all them "packed" into one variable. Not planning to change them, I just need a storage and acces to them. During execution of the app, method will be called many times, such storages will be created many times also (up to 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;

... and so on. I want to return a variable holding both
s and
s. What should I use better insetafd of
? Class or struct, regarding performance?

Thank you!

Answer Source

Here's a sample of how I'd do it:

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

        for (int i = 1; i < WhateverAmountOfOperations; i++)

    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;