Question

My goal is to generate a pseudorandom String consisting of 500000 characters out of a small selection of characters. This is my loop for adding characters to the String:

String alphabet="ABCD";
Random r = new Random();
for (int i = 0; i < 500000; i++) {
    this.setCode((this.getCode() == null ? "" : this.getCode())
    alphabet.charAt(r.nextInt(alphabet.length())));
}

Unsurprisingly this is very slow, so I am looking for ways to get this to perform the >least slow< possible.

Was it helpful?

Solution

Use a StringBuilder to construct your string. Allocate 500000 characters upfront to speed it up a little:

StringBuilder sb = new StringBuilder(500000);
for (int i = 0; i < 500000; i++) {
    sb.append(alphabet.charAt(r.nextInt(alphabet.length())));
}
String res = sb.toString();

OTHER TIPS

If you're willing to use a third-party library, check out the Apache Commons RandomStringUtils.

int count = 500000;
String alphabet = "ABCD";
String randomString = RandomStringUtils.random(count, alphabet);

On my laptop (MacBook Pro), it took about 20ms to generate a 500K string.

Using a StringBuilder will help, but even more so if you declare the initial size to be the actual length of the expected output. That avoids resizing the internal array of the StringBuilder at runtime. Also, accessing a String's char array directly is a little bit faster than using charAt(int) on String -- the reference is direct instead of making a method reference to the array.

 public static String getRandomString(String characterSet){
    final char[] chars = characterSet.toCharArray();
    final int size = 500000;
    StringBuilder sb = new StringBuilder(size);
    Random rand = new Random();
    for(int i=0;i<size;i++){
        sb.append(chars[rand.nextInt(chars.length)]);
    }
    return sb.toString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top