这是一个实施质量问题。
(BTW, in pure theory, an implementation might have a NULL
pointer which is not an all zero bits word; for such cases the semantics of your §3 is different than those of §1 or §2; but in practice, most common processors today have a linear virtual address space and have their NULL
pointer be a word of all zero bits)
Recent GCC编译器(至少在通常的 x86-64 处理器上),启用了优化(例如gcc -O2
)可能会产生same(或非常相似)机器代码(因为memset
扩展为__builtin_memset
它被专门编译并经常内联),所以使用memset
is not实践中速度较慢(由于矢量化甚至可能变得更快,例如AVX机器指令)
您可以查看使用例如生成的汇编代码gcc -S -fverbose-asm -O2 -march=native
(in some cases, notably when struct xyz
has hundreds of fields, the compiler would even synthesize a call to memset
for your case 1 and 2!)
一般来说,用上面的方法1或2初始化会比方法3更快吗?
在实践中,答案通常是否定的(所以更喜欢readable方法)。如果您非常关心,请对您的代码进行基准测试。
(don't forget that development time also costs money; in many cases your human time is worth more than the few CPU nanoseconds you might win, and generally won't)