使用带有序数类型的 const 参数有什么好处吗? [英] Are there any advantages in using const parameters with an ordinal type?

查看:20
本文介绍了使用带有序数类型的 const 参数有什么好处吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道将字符串参数标记为 const 可以产生巨大的性能差异,但是序数类型呢?使它们 const 有什么好处吗?

我在处理字符串时总是使用 const 参数,但从来没有用于 IntegerPointer、类实例等.

当使用 const 时,我经常需要创建额外的临时变量,这些变量替换现在写保护的参数,所以我想知道:我是否从将序数参数标记为 const 中获得了什么?

解决方案

您需要了解原因,避免货物崇拜编程".将字符串标记为 const 会产生性能差异,因为您不再需要在字符串上使用互锁的 refcount 递增和递减,随着时间的推移,这种操作实际上变得更昂贵,而不是更少更多的核心意味着需要做更多的工作来保持原子操作的同步.这是安全的,因为编译器强制执行此变量不会被更改"约束.

对于通常为 4 字节或更少的序数,没有性能提升.仅当您使用大于 4 个字节的值类型(例如数组或记录)或引用计数类型(例如字符串和接口)时,使用 const 作为优化才有效.

然而,还有另一个重要优势:代码可读性.如果您将某些内容作为 const 传递并且它对编译器没有任何影响,它仍然可以对 产生影响,因为您可以阅读代码并看到意图其中之一是不要修改它.如果您之前没有看过代码(其他人编写的),或者如果您在很长时间后重新使用它并且不记得您最初编写它时的确切想法,那么这可能很重要.

I know marking string parameters as const can make a huge performance difference, but what about ordinal types? Do I gain anything by making them const?

I've always used const parameters when handling strings, but never for Integer, Pointer, class instances, etc.

When using const I often have to create additional temporary variables, which replace the now write-protected parameters, so I'm wondering: Do I gain anything from marking ordinal parameters as const?

解决方案

You need to understand the reason, to avoid "cargo-cult programming." Marking strings as const makes a performance difference because you no longer need to use an interlocked increment and decrement of the refcount on the string, an operation that actually becomes more expensive, not less, as time goes by because more cores means more work that has to be done to keep atomic operations in sync. This is safe to do since the compiler enforces the "this variable will not be changed" constraint.

For ordinals, which are usually 4 bytes or less, there's no performance gain to be had. Using const as optimization only works when you're using value types that are larger than 4 bytes, such as arrays or records, or reference-counted types such as strings and interfaces.

However, there's another important advantage: code readability. If you pass something as const and it makes no difference whatsoever to the compiler, it can still make a difference to you, since you can read the code and see that the intention of it was to have this not be modified. That can be significant if you haven't seen the code before (someone else wrote it) or if you're coming back to it after a long time and don't remember exactly what you were thinking when you originally wrote it.

这篇关于使用带有序数类型的 const 参数有什么好处吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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