-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathcharAt() and deleteCharAt() performance
30 lines (25 loc) · 1.47 KB
/
charAt() and deleteCharAt() performance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Question 1:
I've been wondering about the implementation of charAt function for String/StringBuilder/StringBuffer
in java what is the coomplexity of that ? also what about the deleteCharAt() in StringBuffer/StringBuilder ?
Source: http://stackoverflow.com/questions/6461402/java-charat-and-deletecharat-performance
Solution:
The charAt method is O(1).
The deleteCharAt method on StringBuilder and StringBuffer is O(N) on average, assuming you are deleting a
random character from an N character StringBuffer / StringBuilder. (It has to move, on average,
half of the remaining characters to fill up the "hole" left by the deleted character.
There is no amortization over multiple operations; see below.) However, if you delete the last character,
the cost will be O(1).
There is no deleteCharAt method for String.
For String, StringBuffer, and StringBuilder, charAt() is a constant-time operation.
For StringBuffer and StringBuilder, deleteCharAt() is a linear-time operation.
StringBuffer and StringBuilder have very similar performance characteristics.
The primary difference is that the former is synchronized (so is thread-safe) while the latter is not.
Question 2.
How String.charAt(int i) is implemented in Java?
Source: http://stackoverflow.com/questions/20893802/how-string-charatint-i-is-implemented-in-java
Solution: public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}