Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I optimize my code for generating a pseudorandom String for high speed in Java?

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.

like image 489
Andreas Hartmann Avatar asked May 01 '14 12:05

Andreas Hartmann


3 Answers

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();
like image 165
Sergey Kalinichenko Avatar answered Nov 15 '22 01:11

Sergey Kalinichenko


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.

like image 40
William Brendel Avatar answered Nov 15 '22 02:11

William Brendel


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();
}
like image 44
MadConan Avatar answered Nov 15 '22 01:11

MadConan