💡 What is Lazy Loading in General?
Lazy loading means “load or create something only when it’s needed.”
-
🕑 Not upfront: Don’t load everything at the start.
-
✅ On demand: Load it the moment it’s required.
This saves memory, CPU, and startup time.
🟢 Lazy Loading in C#
✅ Idea
In C#, lazy loading means delay the creation or loading of an object until the first time you actually use it.
🔎 Example Without Lazy
Even if you never use Profile
, it’s created.
🔑 Lazy<T>
The Lazy<T>
class lets you create an object only when accessed.
-
new Lazy<CustomerProfile>(() => new CustomerProfile())
means: “Don’t createCustomerProfile
now. Create it only when.Value
is first accessed.” -
If you never call
Profile
, theCustomerProfile
object is never created.
🏗️ Where It’s Used
-
Loading related data in Entity Framework (Lazy Loading of navigation properties).
-
Heavy objects like configuration data or images.
-
Expensive computations.
🟠 Lazy Loading in Angular
✅ Idea
In Angular, lazy loading means load feature modules (or components) only when the user navigates to that part of the app—instead of loading the entire app code at startup.
🏎️ Why?
-
Faster initial load: Only the code for the current page loads.
-
Better performance for big apps.
🔎 Example Without Lazy Loading
In app.module.ts
you import all modules:
Even if user never visits /admin
, its code is downloaded at startup.
🚀 Lazy Loading with Routing
You split features into separate modules and load them on demand.
app-routing.module.ts
-
Angular will download
admin.module.js
only when user goes to/admin
.
🛠️ Steps
-
Create a feature module, e.g.
AdminModule
. -
Remove it from
app.module.ts
imports. -
Use
loadChildren
in the route.
🧩 Component-level Lazy Loading
You can also load standalone components lazily:
🔑 Tips
-
Keep shared/common components in a separate shared module.
-
Combine with route guards for security.
-
Works great with Angular CLI code splitting.
🆚 Quick Side-by-Side
Feature | C# Lazy Loading | Angular Lazy Loading |
---|---|---|
Purpose | Delay object creation/data loading | Delay module/component code download |
Trigger | First time property is accessed | User navigates to a specific route |
Benefit | Save memory & CPU until needed | Faster initial page load, smaller bundle size |
Example Tool | Lazy<T> class, EF Lazy Loading | loadChildren in Angular Router |
🏁 In One Line:
-
C#: “Don’t create the object until someone asks for it.”
-
Angular: “Don’t download code until the user goes to that page.”
That’s Lazy Loading explained for both C# and Angular in simple English with all the important details.
No comments:
Post a Comment