我已经阅读了几篇关于内联函数调用的文章以及问题/答案,结论是最佳做法是让JIT编译器进行所有优化。这很有道理。
那么内联变量声明呢?编译器是否也会进行优化?
也就是说,像这样的代码:
Dim h = (a + b + c) / 2 'Half-Perimeter
If maxEdgeLength / (Math.Sqrt(h * (h - a) * (h - b) * (h - c)) / h) <= MaximumTriangleAspectRatio Then
'Do stuff here.
End If
比这个性能更好:
Dim perimeter = a + b + c 'Perimeter
Dim h = perimeter / 2 'Half-Perimeter
Dim area = Math.Sqrt(h * (h - a) * (h - b) * (h - c)) 'Heron's forumula.
Dim inradius = area / h
Dim aspectRatio = maxEdgeLength / inradius
If aspectRatio <= MaximumTriangleAspectRatio Then
'Do stuff here.
End If
当然,我更喜欢后者,因为它更易于阅读和调试,但如果存在性能下降,我无法承受。
注意:我已经确定了此代码作为瓶颈 - 不需要有关过早优化的反驳。 :-)