Verbatim and raw string literals in C Sharp (C#) - Time & Space Complexity
We want to see how the time to run code changes when using verbatim and raw string literals in C#.
How does the program's work grow as the string size grows?
Analyze the time complexity of the following code snippet.
string verbatim = @"Line1\nLine2\nLine3";
string raw = """
Line1
Line2
Line3
""";
int lengthVerbatim = verbatim.Length;
int lengthRaw = raw.Length;
This code creates two strings using verbatim and raw literals, then measures their lengths.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the Length property of each string.
- How many times: Twice (constant), independent of string size.
In C#, the Length property of a string returns a stored integer value and takes constant time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 constant operations |
| 100 | 2 constant operations |
| 1000 | 2 constant operations |
Pattern observation: The work remains constant regardless of string size.
Time Complexity: O(1)
String literals are created at compile-time, and .Length is O(1) runtime access to a stored field.
[X] Wrong: "Getting string length counts characters each time, so O(n)."
[OK] Correct: Strings store length as an instance field; access is direct and constant time.
Recognizing O(1) operations like string.Length shows deep understanding of language internals.
"What if we concatenated strings in a loop to build them? How would time complexity change?"