简体   繁体   English

关于内存操作员的C#内存分配

[英]C# Memory Allocation in regards to memory operators

I've been running benchmark tests trying to determine the best way of handling many vector operations. 我一直在进行基准测试,试图确定处理许多矢量操作的最佳方法。 I'm not worried about computational efficiency, but memory allocation so that my program doesn't get a big hit from the garbage collector cleaning up excess vectors in the heap. 我并不担心计算效率,而是担心内存分配,这样我的程序就不会因为垃圾收集器清理堆中多余的向量而大受打击。 The standard vector operations (+, *, normalize) are static operator overloads that take in two vectors and returns a new vector. 标准向量运算符(+,*,normalize)是静态运算符重载,它吸收两个向量并返回一个新向量。 Since these use the new operator, I thought that it would allocate memory in the heap and set the assigning variable to that memory location. 由于这些使用new运算符,因此我认为它将在堆中分配内存,并将分配变量设置为该内存位置。 This got to my initial hypothesis of using methods that would update an existing vector if that vector was the assigning variable. 这是我最初的假设,即使用可以更新现有向量的方法(如果该向量是分配变量)。

This is the standard code that uses Vector operations. 这是使用Vector运算的标准代码。

var object1Pos = new Vector2(10, 5);
var object2Pos = new Vector2(-5, 3);
Vector2 object1Trajectory = (object2Pos - object1Pos).normalized;
object1Trajectory *= 8;
object1Pos += object1Trajectory;

This is the code that uses methods to update a vector. 这是使用方法更新向量的代码。

var object1Pos = new Vector2(10, 5);
var object2Pos = new Vector2(-5, 3);
var object1Trajectory = new Vector2(object2Pos);
object1Trajectory.Add(object1Pos * -1);
object1Trajectory.Normalize();
object1Trajectory.Scale(8);
object1Pos.Add(object1Trajectory);

Running the benchmark test, while the method code is 35% more efficient than the operator code (though the increase isn't that significant) the amount allocated to the heap and cleaned by the garbage collector was the same. 运行基准测试时,虽然方法代码的效率比运算符的效率高35%(尽管增加的幅度并不大),但分配给堆并由垃圾收集器清除的数量是相同的。 This doesn't make sense to me, since this shows that either the vectors generated by the operators are generated on the stack, or they compiler is doing some optimizations so it doesn't have to allocate new memory in the heap. 这对我来说没有意义,因为这表明由运算符生成的向量是在堆栈上生成的,或者它们的编译器正在进行一些优化,因此不必在堆中分配新的内存。 I would like to know how c# allocates memory and what the compiler does so that extra memory isn't allocated that will only be used in the method? 我想知道c#如何分配内存以及编译器会做什么,以便不分配仅在方法中使用的额外内存?

The new operator doesn't mean heap allocation in C#. new运算符并不意味着在C#中分配堆。 Vector2 is most likely a struct, so as long as it is a local variable and you're not doing something special like capturing it in a lambda it will be allocated on the stack even when you use new . Vector2很可能是一个结构,因此,只要它是一个局部变量,并且您没有做像在lambda中捕获它那样的特殊操作,即使使用new它也将被分配在堆栈上。

For additional information on types and associated storage, please see Eric Lippert's great post on the subject. 有关类型和相关存储的其他信息,请参阅Eric Lippert关于该主题的精彩文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM