Simple way to repeat a string

后端 未结 30 3045
清酒与你
清酒与你 2020-11-21 06:55

I\'m looking for a simple commons method or operator that allows me to repeat some string n times. I know I could write this using a for loop, but I wish to avoid f

30条回答
  •  抹茶落季
    2020-11-21 07:24

    I wanted a function to create a comma-delimited list of question marks for JDBC purposes, and found this post. So, I decided to take two variants and see which one performed better. After 1 million iterations, the garden-variety StringBuilder took 2 seconds (fun1), and the cryptic supposedly more optimal version (fun2) took 30 seconds. What's the point of being cryptic again?

    private static String fun1(int size) {
        StringBuilder sb = new StringBuilder(size * 2);
        for (int i = 0; i < size; i++) {
            sb.append(",?");
        }
        return sb.substring(1);
    }
    
    private static String fun2(int size) {
        return new String(new char[size]).replaceAll("\0", ",?").substring(1);
    }
    

提交回复
热议问题