简体   繁体   中英

Query fast with literal but slow with variable

I am using Typeorm for SQL Server in my application. When I pass the native query like connection.query(select * from user where id = 1) , the performance is really good and it less that 0.5 seconds.

If we use the findone or QueryBuilder method, it is taking around 5 seconds to get a response.

On further debugging, we found that passing value directly to query like this,

return getConnection("vehicle").createQueryBuilder() 
                               .select("vehicle")
                               .from(Vehicle, "vehicle") 
                               .where("vehicle.id='" + id + "'").getOne();

is faster than

return getConnection("vehicle").createQueryBuilder() 
                               .select("vehicle")
                               .from(Vehicle, "vehicle") 
                               .where("vehicle.id =:id", {id:id}).getOne();

Is there any optimization we can do to fix the issue with parameterized query?

I don't know Typeorm but it seems to me clear the difference. In one case you query the database for the whole table and filter it locally and in the other you send the filter to the database and it filters the data before it sends it back to the client.

Depending on the size of the table this has a big impact. Consider picking one record from 10 million. Just the time to transfer the data to the local machine is 10 million times slower.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM