Arrays & Strings
Arrays: the foundation
An array stores items in a contiguous block of memory, each reachable by an index. That layout gives arrays their superpower: O(1) access by index. Your app’s lists, feeds and adapters are all backed by arrays/lists under the hood.
val items = arrayOf("a", "b", "c")
val first = items[0] // O(1) — instant
items[1] = "B" // O(1) — set by index
The cost of each operation
- Access by index — O(1).
- Search (does it contain X?) — O(n), you may scan everything.
- Insert/remove in the middle — O(n), items must shift.
- Append at the end — usually O(1) (amortised for dynamic lists).
This is why inserting into the middle of a huge list is slow, while reading by index is instant — knowing this guides your data choices.
Dynamic lists (ArrayList / Swift Array)
The lists you use daily (ArrayList, Kotlin MutableList, Swift Array, JS arrays) are dynamic arrays: they grow automatically by allocating a bigger block and copying. Each individual append is O(1) on average, but a resize is an O(n) copy — usually invisible, but worth knowing for performance-critical code.
Strings are special
A string is essentially an array of characters — and in most mobile languages strings are immutable. Every time you “modify” a string, you actually create a new one. Doing this in a loop is a classic performance bug.
// BAD: O(n²) — builds a new string every iteration
var result = ""
for (word in words) { result += word } // new String each time!
// GOOD: O(n) — StringBuilder mutates in place
val sb = StringBuilder()
for (word in words) { sb.append(word) }
val result = sb.toString()
Use StringBuilder (Kotlin/Java), string interpolation, or efficient joins instead of repeated + concatenation — this matters when building large text or logs.
Common string tasks in apps
- Searching/filtering a list as the user types — do it off the main thread and debounce input.
- Parsing — prefer built-in parsers over manual character loops.
- Normalisation — lowercase/trim once and cache, not on every comparison.
2D arrays / grids
Image data, game boards and grids use 2D arrays. Accessing grid[row][col] is O(1), but iterating the whole thing is O(rows × cols) — keep that off the UI thread for large images.
Common mistakes
- Building strings with
+in a loop (O(n²) and lots of garbage). - Searching a list repeatedly when a set/map would be O(1).
- Inserting/removing in the middle of a large list in a hot path.
Summary: Arrays give O(1) index access but O(n) search and middle inserts. The lists you use are dynamic arrays. Strings are immutable — never concatenate with+in a loop; useStringBuilder. Match the operation to the cost.