Optimize SQL query composition

This is a seemingly trivial change but it should make a measurable difference:
* We memoize conversions of arguments to strings, reducing the number of times we call expensive functions by *at least* 50%. 
* We call `std::string::reserve` to preallocate the buffer we need instead of requiring potentially expensive resizes.

On the non-performance front, change some loops to use C++11 ranged `for` and use `auto` for certain types.