performance improvement for checksum calculations - using MappedByteBuffer

Former-commit-id: 5024926737f1abbae47da5e95615dd2f2bddbcc6
This commit is contained in:
Jeremy Long
2014-07-20 07:54:54 -04:00
parent 8b3894f213
commit 47c817de1c

View File

@@ -17,12 +17,11 @@
*/ */
package org.owasp.dependencycheck.utils; package org.owasp.dependencycheck.utils;
import java.io.BufferedInputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.nio.MappedByteBuffer;
import java.security.DigestInputStream; import java.nio.channels.FileChannel;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.logging.Level; import java.util.logging.Level;
@@ -57,16 +56,20 @@ public final class Checksum {
* @throws IOException when the file does not exist * @throws IOException when the file does not exist
* @throws NoSuchAlgorithmException when an algorithm is specified that does not exist * @throws NoSuchAlgorithmException when an algorithm is specified that does not exist
*/ */
@SuppressWarnings("empty-statement")
public static byte[] getChecksum(String algorithm, File file) throws NoSuchAlgorithmException, IOException { public static byte[] getChecksum(String algorithm, File file) throws NoSuchAlgorithmException, IOException {
MessageDigest digest = MessageDigest.getInstance(algorithm); MessageDigest digest = MessageDigest.getInstance(algorithm);
InputStream fis = null; FileInputStream fis = null;
try { try {
fis = new FileInputStream(file); fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis); FileChannel ch = fis.getChannel();
DigestInputStream dis = new DigestInputStream(bis, digest); MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
//yes, we are reading in a buffer for performance reasons - 1 byte at a time is SLOW digest.update(byteBuffer);
byte[] buffer = new byte[8192]; // BufferedInputStream bis = new BufferedInputStream(fis);
while (dis.read(buffer) != -1); // DigestInputStream dis = new DigestInputStream(bis, digest);
// //yes, we are reading in a buffer for performance reasons - 1 byte at a time is SLOW
// byte[] buffer = new byte[8192];
// while (dis.read(buffer) != -1);
} finally { } finally {
if (fis != null) { if (fis != null) {
try { try {