質問

What is the problem in following example? what happens if millions of Char in the String to be Reversed?

public static String reverseUsingStringBuffer(String source) {
    if(source == null || source.isEmpty()){
        return source;
    }       
    StringBuffer reverse = new StringBuffer();

    for(int i = source.length() -1; i>=0; i--){
        reverse.append(source.charAt(i));
    }

    return reverse.toString();
}

Is following better approach? (beside using api method). What is the good approach for huge String?

public static String reverse(String source) {
    if(source == null || source.isEmpty()){
        return source;
    }       
    String reverse = "";
    for(int i = source.length() -1; i>=0; i--){
        reverse = reverse + source.charAt(i);
    }

    return reverse;
}
役に立ちましたか?

解決

As already said, the String approach is pretty bad. Using StringBuffer is much better, but there's no reason for this rather obsolete class, when StringBuilder can do the same faster.

Even simpler and faster in this case is to use an array:

char[] result = new char[source.length];
for(int i = 0; i < source.length(); ++i) result[source.length() - 1 - i] = source.charAt(i);
return new String(result);

This allocates no garbage at all.... except for the char[], but this is unavoidable as String is immutable and the sharing constructor is package-private (for a good reason).

Note that usually there's absolutely no need to optimize that hard.

他のヒント

No, the first approach is better because it will internally manage your buffers for you. Don't try to outsmart the compiler. Why didn't you append the entire source in one line, which will properly allocate your buffer.

The first one. In the second you use "string = string + string" and this creates one object every time you use "+". I'd sugest StringBuffer.

The first approach is better, StringBuffer is mutable and using string = string+string decrease performance.

You can make it in place as well.

public static String reverse(String s) {
   char[] chars = s.toCharArray();
   for(int i = 0, j = chars.length - 1; i < chars.length / 2; i++, j--) {
     char c = chars[i];
     chars[i] = chars[j];
     chars[j] = c;
   }
   return new String(chars);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top