[英]How to avoid boxing/unboxing of a large dynamic object?
I need to multiply two relatively large matrices and do it many times (in a loop). 我需要将两个相对较大的矩阵相乘并多次执行(在循环中)。 However, the format (type of objects) how these matrices are stored in the memory should be chosen by user.
但是,应该由用户选择这些矩阵如何存储在存储器中的格式(对象类型)。 There are three possibilities:
有三种可能性:
double [,] M1; double [,] M2;
( two-dimensional arrays) (二维数组)
double[][] M1; double [][]M2;
( jagged arrays). (锯齿状阵列)。
Matrix <double> M1;Matrix <double> M2;
( Math Net Numerics format). (Math Net数字格式)。
Each format suits a corresponding method ( taken from a numerical library as you may have already guessed). 每种格式都适合相应的方法(取自您可能已经猜到的数值库)。 I need to avoid boxing and unboxing at all cost ( since its expensive) so the following code will not work for me ( unless you tell me that boxing/unboxing is cheaper than fast matrix multiplication):
我需要不惜一切代价避免装箱和拆箱(因为价格昂贵)所以以下代码对我不起作用(除非你告诉我装箱/拆箱比快速矩阵乘法便宜):
object M1;
object M2;
switch case
{
case 1:
M1 = new double[rows,columns];
.../etc
}
One way to solve it is very straightforward: just to declare 6 matrices( 6 variables) and at runtime initialize two of them. 解决它的一种方法非常简单:只需声明6个矩阵(6个变量)并在运行时初始化其中两个。 But this looks ugly and will make the code much more complicated.
但这看起来很丑陋,会让代码变得更加复杂。
My question: is there any elegant solution of this problem? 我的问题:这个问题有没有优雅的解决方案? I am new to C# but the searching over the site did not help me much.
我是C#的新手,但在网站上搜索对我没什么帮助。
Yes, you are all right, there is no boxing/unboxing here. 是的,你没事,这里没有拳击/拆箱。 I figured out what I want and need to do.
我想出了我想要和需要做的事情。 I will create an interface which declares some matrix methods:
我将创建一个声明一些矩阵方法的接口:
interface MatrixMethods
{
void MatrixIni();
void DoMultiplication();
double ReturnFinalResult();
// etc
}
Then I will use a generic class: 然后我将使用泛型类:
class MatrixStorage <T>
{
protected T M1;
protected T M2;
// etc
}
and finally the needed class: 最后需要的课程:
class MatrixMult<T> : MatrixStorage<T> , MatrixMethods
{
public void MatrixIni()
{
//etc Matrix random ini
}
public void DoMultiplication()
{
// multiplication
}
public double ReturnFinalResult()
{
// compute output
}
MatrixMult(params int[] input)
{
// ini
}
}
and, then I instantiate the class and do calculations: 然后我实例化该类并进行计算:
MatrixMethods newMatrixMult;
newMatrixMult = new MatrixMult<UserMatrixType>(userData);
newMatrixMult.DoMultiplication();
double result = newMatrixMult.ReturnFinalResult
I apologize for a misleading question. 我为一个误导性的问题道歉。 Best
最好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.