Hahah, 91 seconds is definitely bad -- postgres' binary-data escaping method is pretty stupid, and I implemented that encoder more or less as an afterthought. The performance improvement of your code is impressive... but it is indeed hideous. I'll look into this in the next few days, I'm still hoping I can find a middle ground -- something that performs decently but does not require four screenfuls of c code ;)
Cheers, Marijn