Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Performance 检查if(false){}else{if(false){}和if(false){}else if(false){}之间的性能_Performance_If Statement - Fatal编程技术网

Performance 检查if(false){}else{if(false){}和if(false){}else if(false){}之间的性能

Performance 检查if(false){}else{if(false){}和if(false){}else if(false){}之间的性能,performance,if-statement,Performance,If Statement,请帮助检查下面两个块代码之间的性能。当运行时忽略图形元素和相同的条件时,我认为两者是相同的 // Block I if(condition1) { // Do something } else { if(condition2) { // Do something } else { if(condition3) {

请帮助检查下面两个块代码之间的性能。当运行时忽略图形元素和相同的条件时,我认为两者是相同的

// Block I if(condition1) { // Do something } else { if(condition2) { // Do something } else { if(condition3) { // Do something } else { if(condition4) { // Do something } } } } //-------------------------------- // Block II if(condition1) { // Do something } else if(condition2) { // Do something } else if(condition3) { // Do something } else if(condition4) { // Do something }
救救我

假设您没有指定的语言是C,那么您可以通过比较gcc的汇编输出来验证您的两个代码段是否生成完全相同的代码:

#!/bin/bash
diff <(gcc -O0 -S -o - -x c - <<EOF
extern int condition1();
extern int condition2();
extern int condition3();
extern int condition4();
extern void do_something1();
extern void do_something2();
extern void do_something3();
extern void do_something4();

void main() {
    if(condition1())
    {
       do_something1();
    }
    else
    {    if(condition2())
        {
           do_something2();
        }
        else
        {    if(condition3())
            {
               do_something3();
            }
            else
            {    if(condition4())
                {
                   do_something4();
                }
            }
        }
    }
}
EOF
) <(
gcc -O0 -S -o - -x c - <<EOF
extern int condition1();
extern int condition2();
extern int condition3();
extern int condition4();
extern void do_something1();
extern void do_something2();
extern void do_something3();
extern void do_something4();

void main() {
    if(condition1())
    {
       do_something1();
    }
    else if(condition2())
    {
       do_something2();
    }
    else if(condition3())
    {
       do_something3();
    }
    else if(condition4())
    {
       do_something4();
    }
}
EOF
)
这不会产生任何输出。您可以通过从其中一个函数中删除最后一个条件并观察它现在显示的差异来证明测试是有效的


由于这两个块的汇编语言输出是相同的,可以推断出性能特征必须完全相同。

放置记录器并检查……为什么你认为添加括号可能会有所不同?我会认为这是过早的优化,除非你真的有性能问题,否则你不应该这么做。此外,您可能会认为编译器无论如何也会将其转换为一个选项。您的计划将有十几个其他地方,您可以赢得比这里更多的性能。如果您在某个虚拟机中运行,您的虚拟机甚至可能在运行时执行优化,具体取决于您的实际数据流,也就是说,性能差异可能太小,对任何非平凡的应用程序都不重要。请告诉我们您使用的是哪种语言-此语法在多种语言中有效。