Ash*_*nko 3 language-agnostic performance
Consider these to options
if(successful)
{
if(condition)
{
//do something
}
if(condition)
{
//do something
}
...
}
Run Code Online (Sandbox Code Playgroud)
or
if(successful)&&(condition)
{
//do something
}
if(successful)&&(condition)
{
//do something
}
...
Run Code Online (Sandbox Code Playgroud)
想象一下有100个if语句.
效率有什么不同吗?
提前致谢.
JUS*_*ION 10
这有两个正确的答案.其他一切都是无稽之谈.
首先使代码正确.然后测量它的性能.然后优化如果需要的话.其他一切都是无稽之谈.
这一切都取决于评估successful表达的成本.
您还应该注意,这两个版本在语义上不相同,因为if-expression的评估可能有副作用1.
如果您确实面临性能问题然后测量,请不要猜测.测量将是了解性能真实情况的唯一方法.
1要从评论中解释一个问题,这里有一个简单的例子,您会得到不同的行为:
该方法CreateProcess具有启动新进程的副作用,并通过返回指示成功创建true:
bool CreateProcess(string filename, out handle) { ... }
if (CreateProcess("program.exe", out handle))
{
if (someCondition)
{
handle.SomeMethod(...);
}
if (someOtherCondition)
{
handle.SomeOtherMethod(...);
}
}
Run Code Online (Sandbox Code Playgroud)
这与以下内容大不相同:
if (CreateProcess("program.exe", out handle) && someCondition)
{
handle.SomeMethod(...);
}
if (CreateProcess("program.exe", out handle) && someOtherCondition)
{
handle.SomeOtherMethod(...);
}
Run Code Online (Sandbox Code Playgroud)