The stackoverflow answer is suboptimal in that they retrieve all the revision contents for discarding them. Just listing revision ids would be enough for the counting (the most expensive field being the content, the other items will be in the same row).
It is possible to get such list from a SQL query, which should be a bit more efficient. Nonetheless, it will be expensive.