Which line options are vice versa better?

I am interested to know which version of the program is the best execution time.
Both options look easy to implement. But what is better to use and in what cases?

String reverse:

public static String reverse(String s)
{
    String rev = "";
    for (int i = s.length() - 1; i >= 0; i--)
        rev += s.charAt(i);
    return rev;
}

StringBuilder reverse:

public static String reverse(String s)
{
    StringBuilder rev = new StringBuilder();
    for (int i = s.length() - 1; i >= 0; i--)
        rev.append(s.charAt(i));
    return rev.toString();
}
+5
source share
4 answers

in two cases: I prefer the second

because the compiler will convert the first of :

rev += s.charAt(i);

to:

(new StringBuilder()).append(rev).append(s.charAt(i)).toString();

But see the worst case scenario :

public class Main
{
    public static void main(String[] args)
    {
        long now = System.currentTimeMillis();
        slow();
        System.out.println("slow elapsed " + (System.currentTimeMillis() - now) + " ms");

        now = System.currentTimeMillis();
        fast();
        System.out.println("fast elapsed " + (System.currentTimeMillis() - now) + " ms");
    }

    private static void fast()
    {
        StringBuilder s = new StringBuilder();
        for(int i=0;i<100000;i++)
            s.append("*");      
    }

    private static void slow()
    {
        String s = "";
        for(int i=0;i<100000;i++)
            s+="*";
    }
}

the output will be:

slow elapsed 173 ms
fast elapsed 1 ms
+6
source

Nothing special about what you can just do:

new StringBuilder(str).reverse().toString();

, StringBuilder reverse - , GC , , .

+5

String java , String , StringBuilder - , , StringBuilder .
char , , String

char[] arr = s.toCharArray();
char tmp;
int maxIndex = arr.length-1;
for( int i = arr.length>>2; i>=0;i--) {
  tmp = arr[i];
  arr[i] = arr[maxIndex-i];
  arr[maxIndex-i] = tmp;
}
return new String(arr);

. javadoc: StringBuilder, String
StringBuilder , ,

0

Some interesting details.
We can write a recursive function to change the string and not use any loops. Use the String method substring():

public static String reverse(String s) {
   int N = s.length();
   if (N <= 1) return s;
   String a = s.substring(0, N/2);
   String b = s.substring(N/2, N);
   return reverse(b) + reverse(a);
}

How effective is this method?
This method has linear time .

0
source

All Articles