Efficiency with Queries

So originally I was looking to try to make my code more efficient in the backend with looped calls. I had a situation where I would put an external API call in a loop and that ended up with huge latency issues.

So I asked my developer friend is there a way to more efficiently make calls without using a loop for x amount of times. In addition to telling me that we should try to refrain from making long requests in a loop, he suggested to change the queries I was using in the backend.

In this example, I want to store lists and todos in separate keys in a hash so I can render a list’s todos in the front-end.

Screen Shot 2017-03-13 at 17.43.09.png

Originally, I was making my query like this, where I find all of the objects in List in Activerecord, loop through the @lists, and put the todo elements in a hash that consists of list and todo.

My friend suggested me to do things this way:

Screen Shot 2017-03-14 at 12.02.22

This allows me to make one query, where I load the List and the Todo elements included in each List element, if applicable.

If I recall, this speeds up the procedure because we are doing one less query, which cuts our runtime by 1.

Cool technique that I learned, and I will definitely try to learn more advance SQL queries to improve future queries, as doing things at the database level is the fastest.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s