Strict null checks and safety in Typescript - Time & Space Complexity
We want to see how strict null checks affect the speed of TypeScript code.
How does adding safety checks change how long the code takes to run?
Analyze the time complexity of the following code snippet.
function findNameLength(name: string | null): number {
if (name === null) {
return 0;
}
return name.length;
}
const names: (string | null)[] = ["Alice", null, "Bob", "Charlie"];
const lengths = names.map(findNameLength);
This code checks each name for null before getting its length, ensuring safety.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The map function loops over each item in the array.
- How many times: Once for each element in the names array.
Each name is checked once, so the work grows directly with the number of names.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and length reads |
| 100 | About 100 checks and length reads |
| 1000 | About 1000 checks and length reads |
Pattern observation: The number of operations grows evenly as the input grows.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items checked.
[X] Wrong: "Adding null checks makes the code much slower, like doubling the time."
[OK] Correct: Null checks add a tiny step per item, but the overall time still grows evenly with input size, not doubling or squaring.
Understanding how safety checks affect performance shows you can write code that is both safe and efficient, a skill valued in real projects.
"What if we changed the array to include nested arrays of names? How would the time complexity change?"