Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Most Efficent way to traverse a String [duplicate]

Tags:

java

string

Possible Duplicate:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?

What I'm considering is time and efficiency. With those in mind, which method (among the ones below or others not mentioned) is the most efficient way to go through each character of a string?

String str = "Foo Bar";
for(int i=0;i<str.length();i++)
   System.out.println(str.charAt(i)); // access the character using .charAt()

for(char letter: str.toCharArray)
   System.out.println(letter);       // use for-each loop with the char array.

Again, there might be a better way to do this, but I also am curious if there is are major time/resources differences between the two above.

like image 308
Zchpyvr Avatar asked Nov 09 '12 00:11

Zchpyvr


People also ask

Which is the best way to find if a string has duplicate characters?

To find the duplicate character from the string, we count the occurrence of each character in the string. If count is greater than 1, it implies that a character has a duplicate entry in the string. In above example, the characters highlighted in green are duplicate characters.

What is the best way to reverse a string in Java?

By Using StringBuilder StringBuilder or StringBuffer class has an in-build method reverse() to reverse the characters in the string. This method replaces the sequence of the characters in reverse order. The reverse method is the static method that has the logic to reverse a string in Java.

How do you repeat the same string in Java?

repeat() method is used to return String whose value is the concatenation of given String repeated count times. If the string is empty or the count is zero then the empty string is returned.


2 Answers

The first version is more efficient. The second version of the code will end up being slower and use more memory because of the cost of creating and filling the new char[] with toCharArray().

For long strings (more than 512 chars, approximately), the fastest way to inspect the string is to use reflection to access the backing char[] of the String (but only works up to Java 8, because of Compact Strings):

String data = "a really long string";
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
char[] chars = (char[]) field.get(data);

for (int i = 0, n = chars.length; i < n; i++)
    System.out.println(chars[i]);

By using the above approach, we were able to avoid entirely the need to create a new char[] and also to pay the cost of an extra method call to charAt() in each iteration.

Take a look at this post, the answer contains detailed benchmarks. The best of both worlds, but anyway it was a hack and it no longer works.

like image 175
Óscar López Avatar answered Nov 15 '22 07:11

Óscar López


The first method is faster since toCharArray has to copy over the internal character array of the string before it returns anything, whereas charAt accesses the elements from this internal array directly, making it more efficient.

In other words, charAt is O(1) and toCharArray is O(n). Now, both of those methods of traversing the string will be O(n), but the second will have a higher 'leading coefficient' than the first.

You can see all this if you look at the source code for the String class.

like image 28
arshajii Avatar answered Nov 15 '22 08:11

arshajii