Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good way to create 1MB String?

Tags:

java

string

I want to create 1MB String for benchmark,so I writed code as follow:

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();
}

I feel that this method createString is not good and stupid

Any idea to optimize the createString method?

like image 605
Koerr Avatar asked Jun 19 '12 07:06

Koerr


1 Answers

How about:

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);
like image 144
Jon Skeet Avatar answered Sep 21 '22 11:09

Jon Skeet