java 创建 1MB 字符串的好方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11096492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's a good way to create 1MB String?
提问by Koerr
I want to create 1MB String for benchmark,so I writed code as follow:
我想为基准创建 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();
}
I feel that this method createString
is not good and stupid
感觉这个方法createString
不好而且笨
Any idea to optimize the createString
method?
有什么想法可以优化createString
方法吗?
回答by Jon Skeet
How about:
怎么样:
char[] chars = new char[size];
// Optional step - unnecessary if you're happy with the array being full of char[] data = new char[1000000];
Arrays.fill(chars, 'f');
return new String(chars);
回答by anoop
You can simply create a large character array.
您可以简单地创建一个大字符数组。
String str = new String(data);
If you need to make a real String
object, you can:
如果你需要制作一个真实的String
物体,你可以:
char[] s = new char[1024 * 1000];
String str = String.copyValueOf(s);
回答by Koerr
static String createString(long size){
StringBuilder o=new StringBuilder(size);
for(int i=0;i<size;i++){
o.append("f");
}
return o.toString();
}
回答by Premraj
Create a character array and use new String(char[])
constructor.
创建一个字符数组并使用new String(char[])
构造函数。
回答by The Original Android
How about using class StringBuilder instead of StringBuffer? StringBuilder should be faster since it is not synchronized unlike StringBuffer.
使用类 StringBuilder 而不是 StringBuffer 怎么样?StringBuilder 应该更快,因为它不像 StringBuffer 那样同步。
Perhaps you can increase performance by setting the compiler flags to increase the Heap memory and Virtual memory. It can not hurt certainly.
也许您可以通过设置编译器标志来增加堆内存和虚拟内存来提高性能。它肯定不会受伤。
回答by Axel
Use StringBuilder and set the capacity:
使用 StringBuilder 并设置容量:
new String(ByteBuffer.allocate(1024).array());
回答by Calvin
Allocate a 1024 byte ByteBuffer, then construct new String out of its backing array.
分配一个 1024 字节的 ByteBuffer,然后从其支持数组中构造新的 String。