Memory efficiency limits retained data and releases unneeded resources so applications use less memory, remain stable, and avoid performance degradation. The practical rule is simple: acquire resources late, release them early, and make cleanup explicit. section 8.4.6
Apply the pattern by reducing both retained application data and unreleased operating-system resources:
- Process large datasets in chunks instead of loading them entirely into memory. section 8.4.6
- Use paginators, database cursors such as Java ResultSet, or iterators to fetch only part of a dataset at a time. section 8.4.6
- Divide large workloads into batches that fit comfortably within available memory. section 8.4.6
- Release file handles, sockets, and similar OS resources as soon as processing finishes. section 8.4.6
- Control cache growth and remove oversized or unnecessary structures rather than increasing RAM by default. section 8.4.6
private static final Map<String, UserProfile> CACHE = new HashMap<>();
public static UserProfile getUserProfile(String userId) {
if (CACHE.containsKey(userId)) {
return CACHE.get(userId);
}
UserProfile profile = loadProfileFromDatabase(userId);
CACHE.put(userId, profile);
return profile;
}
Inspect how an unbounded static cache retains every loaded user profile, illustrating a common source of growing memory use. section 8.4.6
Language-specific cleanup constructs make the same intent safer: Java try-with-resources, C# using, Python with context managers, Go defer, and Rust ownership with Drop. Optimize conservatively; a small memory saving may not justify harder-to-understand code. section 8.4.6 section 8.5.2
