C#数组与C ++数组和垃圾收集器的比较 [英] C# arrays compared to C++ arrays and the garbage collector

查看:78
本文介绍了C#数组与C ++数组和垃圾收集器的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一位C ++程序员,试图把我的头放在C#上,发现我担心的事情。
要声明一个数组,必须使用New运算符对吗?
但是,这是否会使垃圾收集器参与其中?

I'm a C++ programmer trying to wrap my head around C# and found something I'm concerned about. To declare an array, you have to use the New operator right? But wont that get the garbage collector involved?

如果我有一个函数正在创建一个仅在该函数中使用的数组,那是假设的吗?每帧数千次,对New运算符的所有调用是否会为垃圾收集器带来大量开销?

Hypothetically if I had a function that was creating an array just for use within that function and it was being called thousands of times per frame, wouldn't all those calls to the New operator create a significant overhead for the garbage collector?

在C ++中,这些将是在堆栈上声明的数组函数结束后,该范围将立即超出范围,并且性能开销将降至最低,但是在C#中,我担心在这种情况下垃圾收集器会占用多少性能。

In C++ these would be arrays declared on the stack that would drop out of scope as soon as the function ends and the performance overhead would be minimal but in C# I'm worried how much performance the garbage collector might take up in this case.

那么我是否正在考虑正确的方法?
这里是否涉及垃圾收集器,会引起问题吗?
是否有更好的 C#方法来做到这一点?

So am I thinking about this the right way? Is the garbage collector involved here and will it cause problems? Is there a better "C# way" to do this?

推荐答案

基本上,不用担心垃圾收藏家,它知道自己在做什么,而且真的很擅长。

basically, don't worry about the garbage collector, it knows what it's doing and it's really good at it.

如果您正在处理图像,那么是的,您可能会遇到问题...但是您可以解决此问题,例如可以使用stackalloc http://msdn.microsoft.com/en-us/library/cx9s2sy4.aspx

If you are doing image stuff, then yes, you may run into problems... you can step around this though, for instance you can use stackalloc http://msdn.microsoft.com/en-us/library/cx9s2sy4.aspx

,但这意味着您的代码必须设置为不安全。

but it means your code will have to be set to "unsafe".

int* frameData;
frameData = stackalloc int[200];

这篇关于C#数组与C ++数组和垃圾收集器的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆