版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
背景:配合大数据组生成测试数据,做测试使用,第一次运用递归的方式生成的数据用例使用体验不友好:速度慢,消耗内存。于是第二次修改了递归拼接字符串的方法,修改为时间复杂度更低的for循环来操作,仅仅使用了16秒就生成了y一亿条数据。
- 测试Demo如下
static String newLine = "\r\n";// windows下换行符号
static StringBuffer sbrNew = new StringBuffer(1000000);// 创建sbrNew
static int count = 1;
public static void main(String[] args) throws Exception{
long startTime = System.currentTimeMillis();
System.err.println("开始时间:" + startTime);
// 1. 创建文本所在目录,建议提前建好 D:\\test_data
File file = new File("D:\\test_data\\data_new.txt");
// 2. 获取该文件的缓冲输出流
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
// 3. 写入信息
int flagCount = 1;
// 制定StringBuffer大小,防止扩容产生不必要的开销
StringBuffer sbr = new StringBuffer(1000000);
while (true) {
if(flagCount <= 10000) {
// 4. 递归拼接需要写入文件的文本
sbr = getJoinStr(false,count,1);
bufferedWriter.write(sbr.toString());
bufferedWriter.flush();// 清空缓冲区
count = count + 10000;
flagCount++;
}else {
break;
}
}
bufferedWriter.close();// 关闭输出流
long endTime = System.currentTimeMillis();
System.err.println("结束时间:" + (endTime -startTime) +"ms");
}
- 拼接字符串方法 getJoinStr
/**
* count 当前起始数量,
* clazz 组装名称,可按照需求改写
* name 第二个字段,也可自定义
* 拼接不重要,内容随时可以更改,所以传参也没有要求。
*/
public static StringBuffer getJoinStr(int count, String clazz, String name) {
int flagCount = 1;
StringBuffer sbr = new StringBuffer(100000);
while (flagCount <= 10000){
sbr.append(clazz + count + " " + name +" " + count + newLine);
count++;
flagCount++;
}
// System.out.println("第" + count +"次进入");
return sbr;
}
- 这是第一次使用递归方式拼接字符串的方法,这种方法时间复杂度非常高,已废弃,这里提出来仅供参考
/**
* @param flag 条件
* @param count 计数器
* @param first 是否首次进入
*/
public static StringBuffer getJoinStr(boolean flag, int count, int first) {
if (first == 1) {
sbrNew = new StringBuffer(1000000);
}
System.out.println("第" + count +"次进入");
if(flag) {
return sbrNew;
} else {
// 拼接字符串可以按照自定义规则
sbrNew.append("ClazzUID" + count + " name " + count + newLine);
if(count%4000==0) {// 这里要注意,超过一定值会内存溢出,一般不修改ide内存的情况下,在5000左右就是极限
flag = true;
}
count++;
return joiningStr(flag,count,0);
}
ps:小号已注销,这是前几天刚刚写过的一篇文章,特此记录。