Bikash Mohapatra’s Post

Iterating a String wrong costs O(n²) — here's the fix. Most Java devs write this without thinking twice:  String s = "transaction_id_9823";  for (int i = 0; i < s.length(); i++) {    process(s.charAt(i));  } It looks fine. But here's what's actually happening under the hood. ──────────────────────── charAt(i) — Index into the string directly ✅ O(1) per access — no allocation ✅ Zero memory overhead ✅ Lazy — only touches chars you actually use ⚠️ Can get painful if length() is re-evaluated inside old loops toCharArray() — Converts the whole string into a char[] ✅ Clean syntax for enhanced for-loops ✅ Safe for mutation (great for parsing logic) ⚠️ Allocates a full char[] copy — O(n) memory upfront ⚠️ Wasteful if you exit early (e.g. validation short-circuits) ──────────────────────── In our Kafka message validation pipeline, incoming payment strings can be 500+ chars. Switching bulk validators from toCharArray() to charAt() cut heap allocations by ~40% in high-throughput bursts. Rule of thumb: → Read-only iteration? Use charAt() → Need to mutate or pass char[]? Use toCharArray() → Modern Java (11+)? Consider chars() stream for functional style ──────────────────────── What's your default when you iterate a String? Drop it in the comments — curious where the team lands. #Java #CoreJava #StringHandling #FinTech #BackendEngineering

  • diagram

To view or add a comment, sign in

Explore content categories