Random string generation in Java

Posted on


Can random string generation be faster in Java?

Here is my current code

import java.util.ArrayList;
import java.util.List;

public class FastestStringGeneration {

    private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final char[] ch = ALPHA_NUMERIC_STRING.toCharArray();
    private static final java.util.concurrent.ThreadLocalRandom random = java.util.concurrent.ThreadLocalRandom.current();

    public static void main(String[] java) {
        // warmup code
        String[] warmUp = new String[10000];
        for (int j=0; j<10000; j++){
           warmUp[j] = getAlphaNumeric(1024);
        // real code begins
        int numIterations = 1000000;
        String[] randomStrings = new String[numIterations];
        long start = System.currentTimeMillis();
        for(int i=0; i<numIterations; i++){
            randomStrings[i] = getAlphaNumeric(1024);

    public static String getAlphaNumeric(int len) {
        char[] c = new char[len];
        for (int i = 0; i < len; i++) {
            c[i] = ch[random.nextInt(ch.length)];
        return new String(c);

The total time it takes to generate 1 million random strings is about ~ 5.9 seconds. Can it be faster?

I was using java.util.Random but when I changed to java.util.concurrent.ThreadLocalRandom according to comments below I got the most performance improvement!


If the length is always identical you can save 1000000 calls to new().

Because new String(char[]) uses Arrays.copyOf(), you don’t need a new char[] in every loop.

private static int ourlen = 1024;
private static char[] chars = new char[ourlen];

public static String getAlphaNumeric() {
    for (int i = 0; i < ourlen; i++) {
        chars[i] = ch[random.nextInt(ch.length)];
    return new String(c);

Leave a Reply

Your email address will not be published. Required fields are marked *