vipindasks's avatar

Are Eloquent relations faster?

Hi,

Rather than the powerful method chaining and querying capabilities of Eloquent relationships, are they faster than the raw queries. From a performance point of view which should be preferred provided, we are developing web services or API in Lumen?

Thanks.

0 likes
3 replies
bobbybouwmann's avatar

It completely depends on your project and what kind of queries you run.

If you need to do a huge query with multiple tables and you only need to fetch some fields, relations are not faster because it performs multiple queries. It's better to use a join than, which is also provided by Eloquent.

If you download the Laravel Debugbar you can see what queries are run and how fast they are. It's recommended to check this for your codebase and if you find queries to be slow, you might need to refactor them to some repository or service that is doing the join for you ;)

Let me know if you need code example and more explanations :D

2 likes
gregrobson's avatar
Level 6

Raw queries will be faster to compile - as the Laravel framework has to take the tables, joins, filters etc and write out the query for your needs. In the vast majority of cases this is going to take milliseconds and unless you have very high performance requirements it's not a big consideration.

The only caveat is that Eloquent will build queries based on the logic that's coded into it. For some complex queries (lots of joins, and WHERE constraints) it might build a query that "technically works" and brings back the right data, but that query is not optimised for the database engine. e.g. you could write a query with subqueries, but if you are using Postgres, you might be able to rewrite it using Common Table Expressions and this might be executed faster by the DBMS and still bring back the correct data.

robrogers3's avatar

the only issue I've run into related to performance with eloquent is not the queries but the hydration, even if you cache results it takes time to rehydrate the objects. So for this was something I learned the hard way.

Other than that, Eloquent just uses the QueryBuilder which just builds up sql for your query.

Please or to participate in this conversation.