第一代码段更快:如何可以在文件多次写入比单个一个
// code is a private "global variable" for the class
// SourceCodeBuilder is a class that uses StringBuilder()
// basically it is based on String(s), formatted and with many appends depending on the "loc()" calls (see below)
private SourceCodeBuilder code = new SourceCodeBuilder();
[...]
// create "file.txt" and call algorithm
fileOut = new FileWriter("file.txt");
for (int i=0; i<x; i++) {
algorithm();
}
凡算法()是这样的方法:
private void algorithm() {
for (int i=0; i<y; i++) {
code.loc("some text");
code.loc("other text");
...
}
// after "building" the code value I wrote it on the file
fileOut.write(code.toString());
fileOut.flush();
code.free(); // this call "empties" the code variable (so the next time algorithm() is called it has the code var sets to "" - it frees a lot of memory)
// basically it calls "setLength(0)" method of StringBuilder
}
当我在大型文本文件中执行所有这些操作需要大约4500ms的执行时间和少于60MB的内存。
然后我试着用这个其他的代码。 第二一段代码:
private SourceCodeBuilder code = new SourceCodeBuilder();
[...]
// create "file.txt" and call algorithm
fileOut = new FileWriter("file.txt");
for (int i=0; i<x; i++) {
algorithm();
}
fileOut.write(code.toString());
fileOut.flush();
fileOut.close();
如果此时算法()是这样的方法:
private void algorithm() {
for (int i=0; i<y; i++) {
code.loc("some text");
code.loc("other text");
...
}
}
它需要更多的内存大于250MB(和它的确定,因为我不调用代码变量的“free()”方法,所以它是一个“连续”附加在同一个变量上),但是令人惊讶的是它需要超过5300ms才能执行。 这比第一个代码慢了大约16%,我无法向自己解释原因。
在第一个代码中,我会在“file.txt”上多次写入多个文本块。在第二个代码中,我写了一大段文字,但只有一次,在“file.txt”上,并使用了更多的内存。随着第二个代码,我期待更多的内存消耗,但没有更多的CPU消耗(仅仅因为有更多的I/O操作)。
结论:即使第一个代码比第二个执行更多的I/O操作,第一个代码也比第二个快。为什么?我错过了什么吗?
你在这里的措辞很混乱;目前还不清楚哪个是哪个,你的基准测试哪个更好,等等。 –
我试图更好地解释自己......你不了解什么? – HBv6
StringBuilder是否必须在每次达到一定长度时重新分配它? –