My best work happens at 2am, at about 4am I am too tired and get slow and get stuck, I think even then code quality suffers only a little bit.
That's just my experience, I believe it happens because if I am working at that time, I am hyped and or in the zone. There is a sort of second wind involved. The lack of distractions also helps I guess.