这是一段用C++编写的代码:
Vector2f GetCenterLong(float width, float height)
{
const float x = width / 2;
const float y = height / 2;
return Vector2f(x, y);
}
Vector2f GetCenterShort(float width, float height)
{
return Vector2f(width / 2, height / 2);
}
以下是使用
x64 msvc v19.21和
-Ox优化生成的汇编代码。您可以注意到两个函数之间没有任何区别。
__$ReturnUdt$ = 8
width$ = 16
height$ = 24
Vector2f GetCenterLong(float,float) PROC
mulss xmm1, DWORD PTR __real@3f000000
mov rax, rcx
mulss xmm2, DWORD PTR __real@3f000000
movss DWORD PTR [rcx], xmm1
movss DWORD PTR [rcx+4], xmm2
ret 0
Vector2f GetCenterLong(float,float) ENDP
__$ReturnUdt$ = 8
width$ = 16
height$ = 24
Vector2f GetCenterShort(float,float) PROC
mulss xmm1, DWORD PTR __real@3f000000
mov rax, rcx
mulss xmm2, DWORD PTR __real@3f000000
movss DWORD PTR [rcx], xmm1
movss DWORD PTR [rcx+4], xmm2
ret 0
Vector2f GetCenterShort(float,float) ENDP
因此,在编译器可优化的情况下,优先选择可读性而非简洁性。
halfWidth
和halfHeight
可能是更好的名称,除非有与意图相关的更具体的名称。 - Baldrickk