Generate valid random rgb color strings I'd want to see if is possible to optimize performance even further of the following generate color method.

package generacolorrgb;

import java.util.Random;

public class GeneracolorRGB {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Random r = new Random();
        for (int i = 0; i &lt; 100; i++) {
            System.out.println(generateColor(r));
        }

    }

    private static String generateColor(Random r) {
        StringBuilder color = new StringBuilder(Integer.toHexString(r
                .nextInt(16777215)));
        while (color.length() &lt; 6) {
            color.append("0");
        }

        return color.append("#").reverse().toString();

    }

}


Average time it takes on my machine: 1650704.333 ns
Here are some comments related to your code:


Strange place to initialise the Random() – This should either be in within the generateColor() function, or some static initialisation. As it stands now, it looks strange that you need to include the random generator to as a parameter to your function. You are better of using a static initialization
Strange magic number, 16777215 – What is this number? It is not very clear that this is actually the 0xFFFFFF denoting the maximum color number. Also note that nextInt(n) returns a number in the range 0 up to n, but not including n. In other words, you should use 0x1000000
Tricking into being 6 characters – If you add 0x1000000 to the number before converting to hexadecimal you are ensured six digits, and don't need the trick for 6 characters, and can return a substring (instead of using a while loop)


Applying this and your code looks something like this:

package generacolorrgb;

import java.util.Random;

public class GeneracolorRGB {

    static Random randomGenerator;

    static {
        randomGenerator = new Random();
    }


    public static void main(String[] args) {
        for (int i = 0; i &lt; 100; i++) {
            System.out.println(generateColor());
        }
    }

    private static String generateColor() {
        int newColor = 0x1000000 + randomGenerator.nextInt(0x1000000);
        return "#" + Integer.toHexString(newColor).substring(1, 7);
    }
}


Added: An even nicer variant would be:

    private static String generateColor() {
        int newColor = randomGenerator.nextInt(0x1000000);
        return String.format("#%06X", newColor);
    }


Here we let the Formatter handle the formatting issue, and it does indeed look nicer! And we don't need to make sure the random number is above the legal range, as the formatter handles it.