I was just practicing a Javascript solution to a linked list problem (reverse a linked list) when I observed the following. When my code contained this snippet:
while(head!=null) {
temp = head.next
head.next = prev
prev = head
head = temp
}
This took 96ms and some 43.6MB.
It was correct but not in even in the top 50% with respect to speed, so I randomly decided to omit the !=null part of the if statement to see what happens.
while(head) {
temp = head.next
head.next = prev
prev = head
head = temp
}
To my surprise, this reduced time to 63ms and placed it faster than 96% of the solutions! Memory taken increased slightly to 44.2MB as well. But I am confused as to why this simple change caused such a drastic speed up?
If I had to guess, I would say that the second scenario merely checks if head exists, while the first scenario actually evaluates head first and then explicitly compares it to null, or something like this. Even if this is correct, I am surprised by the speed improvement. Any insight on this?
Edit: At a suggestion in the comments I also tried (head !== null), which at 64ms was definitely faster than the first scenario but same as the second!