很久以前,我有一段记忆一直困扰着我,它说与零的比较比任何其他值都快(咳咳 Z80)。
在我正在编写的一些 C 代码中,我想跳过设置了所有位的值。目前这些值的类型是char
但可能会改变。我有两种不同的选择来执行测试:
if (!~b)
/* skip */
和
if (b == 0xff)
/* skip */
除了后者假设 b 是 8bit char 而前者不是,前者是否会因为旧的与零优化技巧相比而更快,或者今天的 CPU 是否超出了这种东西?
很久以前,我有一段记忆一直困扰着我,它说与零的比较比任何其他值都快(咳咳 Z80)。
在我正在编写的一些 C 代码中,我想跳过设置了所有位的值。目前这些值的类型是char
但可能会改变。我有两种不同的选择来执行测试:
if (!~b)
/* skip */
和
if (b == 0xff)
/* skip */
除了后者假设 b 是 8bit char 而前者不是,前者是否会因为旧的与零优化技巧相比而更快,或者今天的 CPU 是否超出了这种东西?
如果它更快,编译器将为您替换它。
一般来说,你不能写出比编译器优化它更好的 C 语言。无论如何,它是特定于架构的。
简而言之,除非亚微纳秒非常重要,否则不要担心
根据我在建筑课上的回忆,我相信它们应该同样快。两者都有 2 条指令。
第一个例子 1. 将 b 取反到临时寄存器 2. 比较临时寄存器等于 0
Second example 1. Subtract 0xff from b into a temp register 2. Compare temp register equal to 0
These are basically identical, and besides, even if your particular architecture requires more or less than this, is it really worth the fraction of a nanosecond? Several minutes have been spent just answering this question.
我想说的是,CPU超出了这些技巧,而不是编译器。
然而,今天的 CPU 已经超越了将速度提高一两个时钟滴答的简单技巧。即使您每秒执行 100,000 次,我们仍然只是在谈论在单核 3Ghz 计算机上增加 0.00003 秒的速度 - 根本不值得您花时间担心这样的事情。
Go with the one that will be easier for the person who is maintaining your code to understand. If you have a successful product, most of the expense in software is in maintenance. If you write cryptic code you add to that expense. If you don't have a successful product, it doesn't matter because no one will have to maintain it. I have been in situations where I had to save every byte I could, and had to resort to tricks like the one you gave, but I only do it as the very very very last resort.