什么时候适合使用条件编译而不是常规的 if-else 语句?
我发现使用 #ifdef 等结构进行条件编译比运行时条件检查有一些好处,例如编译文件大小更小、执行速度可能更快以及调试更容易,但是什么时候适合使用其中一种?当正在评估的条件语句只能在运行时确定时,使用运行时条件检查是否是最佳实践?
在我看来,将 #ifdefs 与常规 if-then-else 语句混合会使代码变得丑陋且难以阅读,因此我倾向于避免条件编译。但是我注意到,在很多 C# 日志类示例中,条件编译用于根据是否定义了 DEBUG/SHIP/TRACE 等符号来确定何时执行日志记录。
I see that there are some benefits to conditional compilation using constructs like #ifdef over runtime conditional checks such as smaller compiled file size, probably faster execution, and somewhat easier debugging, but when is it appropriate to use one over the other? Is it a best practice to use runtime conditional checks when the conditional statement being evaluated can only be determined at runtime?
In my opinion mixing #ifdefs with regular if-then-else statements makes the code ugly and harder to read, so I tend to avoid conditional compilation. However I've noticed that in a lot of C# log class examples conditional compilation is used to determine when to perform logging depending on whether symbols such as DEBUG/SHIP/TRACE are defined.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好尽量减少 #ifdef 的使用。正如您所说,它们使代码更难以阅读和调试。
当针对不同平台或调试/发布版本之间存在差异时,它们可能是不可避免的。
性能可能是使用#ifdef 进行调试的一个考虑因素,但在大多数情况下,用于检查日志级别的额外条件语句的影响可以忽略不计。我想说,在将条件逻辑转换为 #ifdef 之前,您必须分析代码并确定这是一个瓶颈
It's best to minimise the use of #ifdef's. Like you said, they make the code harder to read and debug.
They can be unavoidable when targeting different platforms, or when there are differences between debug/release versions.
Performance could be a consideration to use #ifdef's e.g. for debugging, but in most cases the impact of an extra conditional statement to check for log level would be negligible. I'd say you'd have to profile the code and determine that this is a bottleneck before converting conditional logic to #ifdef's
条件编译应该用于为不同平台编译相同的源代码,或者如果您有不同版本的程序(例如测试版本和完整版本)。
Conditional compilation should be used for things like compiling the same source code for different platforms or if you have different versions of a programm (for example a test version and a full version).