Skip to main content
MR

Eloquent performance: Lazy loading vs Eager loading benchmark

Marcus Rivera Laravel & PHP 258 views
I ran some benchmarks on lazy loading vs eager loading in a project with around 50K records and wanted to share results. Setup: Blog posts with authors, categories, and tags (polymorphic). Lazy loading (N+1 problem): Post::all() then accessing post->author in a loop. Result: 523 queries, 2.8 seconds. Eager loading: Post::with(['author', 'category', 'tags'])->get() Result: 4 queries, 0.12 seconds. That is a 23x improvement. Always use with() to eager load your relations. Also, calling preventLazyLoading() in AppServiceProvider is a lifesaver during development because it throws exceptions when you accidentally lazy load. Anyone have other Eloquent performance tips to share?

2 Replies

SC
Sarah Chen 1 week ago
Great benchmarks Marcus! One more tip: use withCount() instead of loading entire relations when you just need counts. For example, Post::withCount('comments')->get() gives you a comments_count attribute via a single query with a subselect, instead of loading potentially thousands of related records into memory.
EA
Engr Mejba Ahmed 1 week ago
Solid benchmarks. At ElectronicFirst.com we process thousands of orders daily and Eloquent performance is critical. Two more tips from production experience: 1. Use chunk() or lazy() for processing large datasets. Never call Model::all() on a table with 100K+ rows, it will consume all your memory. Model::lazy() streams results and chunk(100) processes in batches. 2. For reporting queries that do not need model features, use DB::table() or raw queries. The Eloquent hydration overhead on 50K+ records is significant. A raw query can be 3-5x faster when you only need aggregates.

Post a Reply