使用具有序数类型的const参数有什么优点吗? [英] Are there any advantages in using const parameters with an ordinal type?
问题描述
const
可以产生巨大的性能差异,但是序数类型呢?通过使他们 const
获得任何东西? 我在处理字符串时一直使用 const
参数,但从来没有使用 Integer
,指针
,类实例等。
使用 const
我经常需要创建额外的临时变量,替代现在的写保护参数,所以我想知道:我是否从标记序号参数获取任何东西,如 const
?
您需要了解原因,以避免货物编织。将字符串标记为const会产生性能差异,因为您不再需要使用字符串上的引用计数的互锁递增和递减,这种操作实际上变得更昂贵,而不会因为时间的流逝而更少,因为因为更多的核心意味着必须做更多的工作来保持原子操作同步。这是安全的,因为编译器强制执行这个变量不会被更改约束。
对于通常为4个字节或更少的ordinals,没有性能提升要有使用 const 作为优化仅在使用大于4个字节的值类型(例如数组或记录)或引用计数类型(如字符串和接口)时有效。
然而,还有另一个重要优点:代码可读性。如果你传递一些东西作为 const ,它对编译器没有任何区别,它仍然可以使你有所作为,因为你可以阅读代码,看到意图是不是要修改这个。如果您以前没有看过代码(其他人写过),或者如果您在很长一段时间后再回来,并且不记得您最初写的时候正在想什么,那么这一点很重要。 p>
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屋!