Use lazy var to Improve Performance
- qmshahzad
- Feb 12, 2025
- 1 min read
Use lazy var to Improve Performance
If you have a property that is expensive to compute and only needed when first accessed, declare it as lazy.
Example:
class UserProfile {
lazy var fullName: String = {
print("Computing full name...")
return "\(firstName) \(lastName)"
}()
let firstName = "John"
let lastName = "Doe"
}
let user = UserProfile()
print(user.fullName) // "Computing full name..." printed only when accessed
print(user.fullName) // Uses cached value, no extra computation

Why Use lazy?
The property is only initialized when first accessed, saving memory and processing time.
Ideal for expensive operations like database queries, API calls, or heavy calculations.
Comments