Now I’m getting deeper into using the IMAP API to pull email from Google, I’m hitting a lot of performance issues. Most of them are on the parsing and database loading side, but while profiling I did discover a few ways I was using IMAP inefficiently. I’ve updated my original PHP/Gmail example with some optimizations. The main speed boost was switching from grabbing all the email headers using imap_headers() just to get the total number of messages in the mailbox. That’s very inefficient, especially on large mailboxes. Instead I just call imap_num_msg() to get the count directly, and that’s much faster. Another wrinkle was asking for the INBOX mailbox to get all the messages. It’s better to look for [Gmail]/All Mail if you want the complete set of non-spam email in case the user has organized their mail into different folders, though you do also get the sent mail as part of that.