while A and While A != None Performance difference


  • 0
    B
    def insertionSortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head==None or head.next == None:
            return head
        p = head.next
        head.next = None
        dumy = ListNode(0)
        dumy.next = head;
        while p != None:
            ptemp = dumy;
            while ptemp.next and p.val > ptemp.next.val:  #Line 0
                ptemp = ptemp.next
            p0= p
            p=p.next
            p0.next = ptemp.next
            ptemp.next = p0
        return dumy.next
    

    This code passed.
    But if change the #Line 0 above to "while ptemp.next != None and p.val > ptemp.next.val:"
    time limit failure.
    Anybody can explain why this two code perform so differently?

    Thanks!


  • 0
    B

    Found the answer online: https://stackoverflow.com/questions/7816363/if-a-vs-if-a-is-not-none
    scroll down to the bottom, it will show the assembler difference:

    """
    if A:

    assembler:
    LOAD_FAST
    POP_JUMP_IF_FALSE

    if A != None:
    assembler:
    LOAD_FAST
    LOAD_CONST 0 (None)
    COMPARE_OP (is not)
    POP_JUMP_IF_FALSE
    """
    two more line assembly.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.