Diesel is really nice library, given Rust’s inflexibility, I mean compared to Ruby/Python. Especially BoxedSqlQuery through into_boxed makes me feel like you can build so many wonderful APIs.
However, I am a bit curious, how much slower a BoxedSqlQuery is ? My understanding is that it’s just a Box and the real difference is that for every method called, heap must be accessed, since it’s doing dynamic dispatch. So can we roughly say that it’s an order of magnitude slower than using Diesel without BoxedSqlQuery? And isn’t that many many orders of magnitude faster than the actual time it takes for the query to execute ? (which should be around 5ms).
I just need to make sure I shouldn’t feel guilty everytime I am using BoxedSqlQuery Is there any other disadvantage using BoxedSqlQuery ?
I do not have any hard number on this, but yes the general consensus is that using a boxed query will not matter in most cases. The only case that comes in my mind where it probably will matter is executing a simple query in a inner hot loop.
So what are the differences between normal queries and boxed queries that could lead to performance differences?
BoxedSelectStatement contains up to 7 heap allocations with trait objects. So constructing such a query involves allocating heap memory 7 times and doing a dynamic dispatch 7 times. Calling a method like
.filter on the select statement will trigger another heap allocation to replace on of the fields in the select statement, but it does not contain a dynamic dispatch.
- Caching such a query in the prepared statement cache will not be as efficient as certain simple queries. In the most optimized case (= where the typed query represents exactly one query on SQL side) we use the type id as cache key and skip the construction of the actual SQL for all but the first query execution on that connection. That’s not possible for boxed queries because they can contain different SQL for the same type.