0

When I do algorithm exercises, I found many people like to transfer a string to charArray before do operations?

I don't understand why do we bother do that? I mean, I can use string.charAt(), why use string.toCharArray() and then charArray[i]? It's the same and even charArray use O(n) memory.

Can anyone explain that to me?

7
  • 1
    Why don't you ask the peoples who have written that code? And this question might also depend on the operations you're talking about. Commented Sep 17, 2015 at 22:05
  • 1
    there are several reasons: String is immutable thus, if you want to manipulate the string it's always faster to generate the charArray first. And the access of an array-element is way faster than charAt. Would expand this to an answer, but since @SotiriosDelimanolis closed the question for no reason... Commented Sep 17, 2015 at 22:11
  • 1
    @Paul The answers in the duplicated question already contain exactly that information. That's what 'duplicate' means. Commented Sep 17, 2015 at 22:31
  • @Paul: I don't usually do Java, but StringBuffer is a mutable string, and still has indexOf() and all the usual String stuff. docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html. So String being immutable isn't sufficient explanation. StringBuffer was in JDK1.0, so it's not new. There must be some other reason it doesn't get used. I'd guess probably working with an array of char is more straightforward. Commented Sep 18, 2015 at 2:20
  • @PeterCordes StringBuffer and String are two completely different things. String is immutable, StringBuffer isn't since it's purpose is to manipulate Strings. But in general it's way faster to manipulate an array than calling charAt. Might be more straightforward aswell, but it's rather a matter of personal coding-style than anything else. Commented Sep 18, 2015 at 11:00

1 Answer 1

1

There are several reasons why people prefer char[] over String and StringBuffer:

  • String is immutable. This means, if you want to manipulate a String without using any utilityclass you'll wind up copying the String pretty often, which results in extremely inefficient code.
  • accessing Characters in a char[] is way faster than using charAt (though it takes some time to convert a String to a char[], which should be considered aswell, when optimizing):

    class Test{
        public static void main(String[] args){
            String s = "a";
            char[] c = new char[]{'a'};
            StringBuffer buffer = new StringBuffer("a");
    
            char x;
    
            long time = System.nanoTime();
            for(int i = 0 ; i < 1000 ; i++)
                x = s.charAt(0);
            time = System.nanoTime() - time;
    
            System.out.println("string: " + time);
    
            time = System.nanoTime();
            for(int i = 0 ; i < 1000 ; i++)
                x = c[0];
            time = System.nanoTime() - time;
    
            System.out.println("[]: " + time);
    
            time = System.nanoTime();
            for(int i = 0 ; i < 1000 ; i++)
                x = buffer.charAt(0);
            time = System.nanoTime() - time;
    
            System.out.println("buffer: " + time);
        }
    }
    

    Running this simple class results in the following output (on my machine, using javaSE 1.8.0 build b132):

    string: 37895
    []: 18948
    buffer: 85659

    So obviously access via char[] is way faster than using a String or StringBuilder.

  • using an Object to manipulate single characters will result in a code stuffed with charAt() and setCharAt(), which might be considered ugly code.

  • Security: String is rather insecure, if the code handles sensitive data, since the immutable String will be stored in memory. This means that the String containing sensitive data will be accessible until the GC removes it from the memory. char[] on the other hand can be simply overwritten at any time and thus remove the sensitive data from memory.

Sign up to request clarification or add additional context in comments.

1 Comment

Java microbenchmarks are pretty meaningless. This runs too quickly for the JIT compiler to do its job. Even cranking the counts way up doesn't help StringBuffer, though, so maybe it's a bad class that doesn't optimize away. Or maybe the JIT-compiler can see that the loops do nothing for the String and array cases, but not StringBuffer. IDK, but it's not much of a test. Still, it's a data point that indicates that StringBuffer might be slower.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.