我可以通过在 C# 中通过引用传递 DateTime 参数来减少内存分配吗?
在 C# 中,与按值传递相比,将 DateTime 引用作为参数传递给函数时,内存分配是否会显着减少?
int GetDayNumber(ref DateTime date)
vs
int GetDayNumber(DateTime date)
函数内的代码在任何情况下都不会修改日期。
In C#, is there any significant reduction in memory allocation when passing a DateTime reference as a parameter to a function as opposed to passing it by value?
int GetDayNumber(ref DateTime date)
vs
int GetDayNumber(DateTime date)
The code inside the function is not modifying the date in any case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
DateTime
是一个 8 字节结构。ref
有 4 或 8 个字节,具体取决于您的目标架构。因此最多可以节省 4 个字节的堆栈内存,这是完全无关的。ref 甚至可能会阻止某些优化,例如将 DateTime 放入寄存器中,从而实际上增加了内存使用。
这是一个明显的过早优化案例。不要这样做。
A
DateTime
is a 8 byte struct. Aref
has 4 or 8 bytes depending on your target architecture. So at best you'd save 4 bytes of stack memory, which is completely irrelevant.It's even likely that
ref
prevents some optimizations, such as placing theDateTime
in a register, thus actually increasing memory use.This is a clear case of premature optimization. Don't do this.
与任何其他类似问题一样,您需要自己计时。一些处理器滴答声会发挥重要作用吗?一些额外的字节会在应用程序的内存消耗中发挥主要作用吗?
抛开微观优化,首先专注于解决实际问题。
As with any other similar question you need to time it yourself. Would a few processor ticks play significant role? Would a few extra bytes play major part in memory consumption in your application?
Leave the micro optimisation and concentrate on real problem solving first.
我不认为内存使用量有任何显着减少,但我相信有一些。
当使用 ref 传递日期时间时,不会像不使用 ref 关键字时那样创建新的日期时间对象
I don't think there's any significant reduction in the memory usage, but I believe there's some.
When passing the datetime with ref there won't be created a new datetime object as when you don't use the ref keyword
但是,您可以,因为 DateTime 是一个结构体并且仅在堆栈上分配,因此开销非常小,因为没有像类那样的堆分配。另外,由于该值作为新实例传递,因此一旦离开该方法,堆栈上的空间就会被释放。
You could, however since DateTime is a struct and only allocated on the stack, there is very little overhead as there is no heap allocation like there is for a class. Also because the value is passed as a new instance, the space on the stack will be freed as soon as you leave the method.
在内部,DateTime 值表示为刻度数,为 64 位长整型。
64 位处理器将需要相同数量的位来发送变量的地址。
但如果在 32 位处理器中工作,您的地址范围将小于日期时间的大小。所以性能可以得到提高。
然而,在实践中,这种差异几乎永远不会被注意到。
Internally, DateTime values are represented as the number of ticks, which is a long of 64 bit.
A 64bit processor will need the same amount of bits to send the address of the variable.
But if working in a 32bit processor, your address range is smaller than the size of the datetime. So the performance could be improved.
However, in practice, the difference is nearly never gonna be noticed.