为什么 Java 中的这段代码比 C++ 快?我需要逐字节比较 2 个文件。例如,比较两个大小为 650mb 的文件时,C++ 需要 40 秒,Java 需要 10 秒。
C++ 代码:
//bufferSize = 8mb
std::ifstream lFile(lFilePath.c_str(), std::ios::in | std::ios::binary);
std::ifstream rFile(rFilePath.c_str(), std::ios::in | std::ios::binary);
std::streamsize lReadBytesCount = 0;
std::streamsize rReadBytesCount = 0;
do {
lFile.read(p_lBuffer, *bufferSize);
rFile.read(p_rBuffer, *bufferSize);
lReadBytesCount = lFile.gcount();
rReadBytesCount = rFile.gcount();
if (lReadBytesCount != rReadBytesCount ||
std::memcmp(p_lBuffer, p_rBuffer, lReadBytesCount) != 0)
{
return false;
}
} while (lFile.good() || rFile.good());
return true;
和Java代码:
InputStream is1 = new BufferedInputStream(new FileInputStream(f1));
InputStream is2 = new BufferedInputStream(new FileInputStream(f2));
byte[] buffer1 = new byte[64];
byte[] buffer2 = new byte[64];
int readBytesCount1 = 0, readBytesCount2 = 0;
while (
(readBytesCount1 = is1.read(buffer1)) != -1 &&
(readBytesCount2 = is2.read(buffer2)) != -1
) {
if (Arrays.equals(buffer1, buffer2) && readBytesCount1 == readBytesCount2)
countItr++;
else {
result = false
break;
}
}