This article highlights several anti-patterns in Java that can significantly degrade performance, even when the code appears to function correctly. One such pattern is string concatenation within loops using the `+` operator, which results in O(n²) copying due to immutability of strings, leading to high memory usage and slower execution times. Another issue is using streams inside loops, where each iteration creates a new stream over the entire list, causing inefficient O(n²) operations. The article also discusses how methods like `String.format()` can be slow in hot paths because they require parsing format strings on every call, leading to unnecessary overhead. Additionally, autoboxing of primitive types into their wrapper classes within loops results in millions of throwaway objects, further impacting performance. By addressing these patterns, the author demonstrates significant improvements in execution time and memory usage.
- Java applications
- Replace string concatenation within loops with `StringBuilder`. Example: Replace `report = report + line + "\n";` with `sb.append(line).append("\n");`.
- Avoid using streams inside loops. Instead, use a single pass approach or merge operations to reduce redundancy. Example: Use `ordersByHour.merge(hour, 1L, Long::sum);` instead of streaming the entire list for each order.
- Minimize usage of `String.format()` in hot paths by replacing it with more efficient methods like `StringBuilder`. For instance, use `"Order " + orderId + " for " + customer + ": $" + String.format("%.2f", amount);` instead of `String.format("Order %s for %s: $%.2f", orderId, customer, amount);`.
- Avoid autoboxing in hot paths by using primitive types. Replace `Long sum = 0L; for (Long value : values) { sum += value; }` with `long sum = 0L; for (long value : values) { sum += value; };`.
In a typical homelab stack, these issues could lead to increased CPU usage and memory consumption in Java applications. For example, the string concatenation issue might cause unnecessary garbage collection if not addressed.