How to create an 'empty if statement' in python

后端 未结 4 949
别那么骄傲
别那么骄傲 2020-12-05 17:45

It\'s very common in C: hacking \'empty if statement\' like this:

if(mostlyhappencondition)
    ;#empty statement
else{
    dosomething;
}

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 18:04

    No, that won’t improve performance. In fact, it doesn’t in C, either. Where did you hear that?

    not/! reads better and should have more or less the same speed.


    And actually tested with gcc -O4:

    #include 
    
    int main(int argc, char *argv[]) {
        for(int i = 0; i < 1000000000; i++) {
            if(!(i < 900000000)) {
                putchar('.');
            }
        }
    }
    

    vs.

    #include 
    
    int main(int argc, char *argv[]) {
        for(int i = 0; i < 1000000000; i++) {
            if(i < 900000000);
            else {
                putchar('.');
            }
        }
    }
    

    #1 took 6.62 seconds and #2 took 6.64 seconds on my computer.

提交回复
热议问题