Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is lazy loading vs eager loading and when should you use each? Lazy loading और eager loading में क्या अंतर है, कब कौन-सा इस्तेमाल करें?

Answer
ApproachBehaviorBest when
Lazy loadingRelated data loaded only when accessedRelated data isn't always needed
Eager loadingRelated data loaded upfront in one queryYou know you'll need related data for every record
// Lazy loading (default) - triggers query when accessed
$post = Post::find(1);
echo $post->author->name; // separate query fired here

// Eager loading - loads relationship upfront
$posts = Post::with('author')->get();
foreach ($posts as $post) {
    echo $post->author->name; // no extra queries
}

Rule of thumb: if you're looping over a collection and accessing a relationship inside the loop, eager load it to avoid N+1 queries.

Approachव्यवहारकब बेहतर
Lazy loadingसिर्फ access होने पर related data load होता हैRelated data हमेशा ज़रूरी नहीं
Eager loadingRelated data पहले से एक query में loadहर record के लिए related data चाहिए
$post = Post::find(1);
echo $post->author->name; // यहाँ query fire होती है

$posts = Post::with('author')->get();
foreach ($posts as $post) {
    echo $post->author->name; // कोई extra query नहीं
}

Was this answer clear?