0

I have a simple question regarding optimization. Let's say I have a function that should return a String with one thousand 'A' characters (the number is arbitrary and might be parametrized later). What would be the best way to go around doing so?

StringBuilder sb = new StringBuilder();
for(int i=0; i<1000; i++)
   sb.append('A');
return sb.toString();

I've come up with this solution utilizing StringBuilder but I feel there should be a better solution, a memcpy of sorts.

Thanks!

2 Answers2

2

Arrays::fill

Demo:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        char[] arr = new char[1000];
        Arrays.fill(arr, 'A');
        String str = new String(arr);
        System.out.println(str);
    }
}

Alternatively, String::repeat

Demo:

public class Main {
    public static void main(String[] args) {
        String str = "A".repeat(1000);
        System.out.println(str);
    }
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • If a character for the fill would be an ASCII char, I would suggest to use a `byte` array instead of the `char` array, and then calling `new String( arr, charset )` with `charset` set to ASCII. But only an experiment could show if my approach is really faster than yours (and still faster than `String.repeat()`). – tquadrat May 22 '20 at 20:55
0

I think you can do it with an array of bytes, and convert that to a string, since you know the size already.

byte[] arr = new byte[1000];
for  (int i = 0; i < arr.length; i ++) arr[i] = 65;
String str = new String(arr);

If a plain byte doesn't work for you, then you could do a char[]. If you need it to be more than that, you can multiply the size by 2 or however many codepoints you need for each character, and again use a for loop (but skip by the number of codepoints your letter takes up)

user
  • 7,435
  • 3
  • 14
  • 44
  • 1
    Your method took 31 seconds on my machine to do 10_000_000 iterations. String.repeat() took 4 seconds. – WJS May 22 '20 at 20:18