Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

delphi - Are there any advantages in using const parameters with an ordinal type?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...