我想为基准创建1MB的字符串,所以我编写了如下代码:

public final static long KB     = 1024;
public final static long MB     = 1024 * KB;
public static void main(String[] args){
    String text_1MB=createString(1*MB);
}
static String createString(long size){
    StringBuffer o=new StringBuffer();
    for(int i=0;i<size;i++){
        o.append("f");
    }
    return o.toString();
}

我觉得这种方法createString不好又愚蠢

有什么想法可以优化createString方法吗?

最佳答案

怎么样:

char[] chars = new char[size];
// Optional step - unnecessary if you're happy with the array being full of \0
Arrays.fill(chars, 'f');
return new String(chars);

09-10 15:30