2013-04-26 85 views
3

我不是一个时髦的专家,只是随时使用它。最新的目标之一是生成一个包含一些随机数据的非常简单的文件。我创建了下面的脚本: Groovy I/O性能问题

out = new File('sampledata.txt') 
Random random = new Random(); 
java.util.Date dt = new java.util.Date(); 

for (int i=0; i<100000; ++i) { 
    dt = new java.util.Date(); 
    out << dt.format('yyyMMdd HH:mm:ss.SSS') + '|box|process|||java.lang.Long|' + random.nextInt(100) + '|name\n' 
} 

现在,我与它的性能实在不解。大约需要1.5分钟分钟才能完成,而用Java或Ruby编写的相同代码需要的时间少于

在Ruby中类似的代码(大约需要1秒执行):

需要 “时间”

File.open("output.txt", "w") do |file| 
    100000.times do 
    line = Time.now.strftime("%Y%m%d %H:%M:%S.%L") + '|box|process|||java.lang.Long|' + rand(100).to_s + '|name' 
    file.puts line 
    end 
end 

任何想法的如何常规处理速度可以改善?

回答

7

左移操作员打开文件,跳转到结束,追加文本,并再次关闭文件...

相反,尝试:

Random random = new Random(); 

// Open the file and append to it. 
// If you want a new file each time, use withWriter instead of withWriterAppend 
new File('sampledata.txt').withWriterAppend { w -> 
    100000.times { 
    w.writeLine "${new Date().format('yyyMMdd HH:mm:ss.SSS')}|box|process|||java.lang.Long|${random.nextInt(100)}|name" 
    } 
} 

(这还得多像Ruby代码在做什么)