Closes #1474 (and reintroduces a performance improvement introduced in cf13f7be039c056d0f1a0d51cc88b5aa2eba640c and backed out in 7227ec1d46bce99ba8c3f70f8a3746e5b01c0593)