Use toCharArray() Wisely

Wenhe Qi
2 min readMar 12, 2021
Photo by Math on Unsplash

When it comes to implement algorithms that deals with strings, I often use two methods in Java String class: charAt() and toCharArray().

They both can perform some of the same functionalities, e.g. loop through each character in a string. Personally I’m a fan of toCharArray() as I can write more compact code and it saves me a lot of typing, especially in more complex logic. Here is a silly example:

void foo(String bar) {
for(char c : bar.toCharArray()) {
System.out.println(c);
}
}

Instead if I re-write the same function using charAt(), it would be something like below:

void foo(String bar) {
for (int i = 0; i < bar.length(); i++) {
System.out.println(bar.charAt(i));
}
}

While I’ve been wondering the performance differences.

First let’s have a look at Java SE 8 source code.

As you may probably know already, String class is immutable in Java. Once a string is created, it can not be modified. Whenever you modify a string, instead of modifying the original string, the methods will return you a new string with the modification.

This is exactly why in toCharArray(). Even though the instance variable value is final, it only means the reference of value can not be changed, you are still able to modify the values of each element in the value array if you have that reference. Hence in toCharArray(), it creates a defensive copy of the original string and returns it to the caller function.

On the other hand, charAt() returns the char value in a specified position directly, since char is a primitive type in Java. It’s safe to do so because the caller only get the value in that position, not reference.

Next let’s talk about complexity.

In toCharArray(), it takes O(n) time to return the result, where n is the length of the string. It also takes O(n) space as it creates a defensive copy of the original string.

In charAt(), it takes O(1) time to return the result as it’s a random access. It also takes O(1) space as we only return the value of the char at specific position. No defensive copy is used.

I’d say it really depends on the algorithm you are implementing to choose which method to use. While after the analysis above, it should be clear that toCharArray() do have some cost when being used. Be wise when choosing the method, especially when the algorithm only needs to loop through the string without returning some new string. It may cost less time to program, but more time and space to run.

--

--

Wenhe Qi

A lifelong learner who has enthusiasm for sharing knowledge; a developer who loves bringing ideas to life.