Python if not == vs if !=

后端 未结 7 1367
轻奢々
轻奢々 2020-12-07 08:09

What is the difference between these two lines of code:

if not x == \'val\':

and

if x != \'val\':

Is one

7条回答
  •  执笔经年
    2020-12-07 08:29

    @jonrsharpe has an excellent explanation of what's going on. I thought I'd just show the difference in time when running each of the 3 options 10,000,000 times (enough for a slight difference to show).

    Code used:

    def a(x):
        if x != 'val':
            pass
    
    
    def b(x):
        if not x == 'val':
            pass
    
    
    def c(x):
        if x == 'val':
            pass
        else:
            pass
    
    
    x = 1
    for i in range(10000000):
        a(x)
        b(x)
        c(x)
    

    And the cProfile profiler results:

    enter image description here

    So we can see that there is a very minute difference of ~0.7% between if not x == 'val': and if x != 'val':. Of these, if x != 'val': is the fastest.

    However, most surprisingly, we can see that

    if x == 'val':
            pass
        else:
    

    is in fact the fastest, and beats if x != 'val': by ~0.3%. This isn't very readable, but I guess if you wanted a negligible performance improvement, one could go down this route.

提交回复
热议问题