快速文件散列大文件

时间:2014-01-04 06:19:36

标签: javascript performance hash

我正在使用sjcl对客户端的文件进行哈希处理,以便在开始完整上传之前检查它们是否存在于服务器上。

然而,它看起来有点慢。哈希8 MB文件大约需要15秒。我不确定是不是因为库很慢,JavaScript很慢,或算法本身很慢。它正在使用sha256,这可能对我需要的东西有点过分。速度是关键 - 加密安全和冲突并不是特别重要。

有更快的方法吗?

$(document).on('drop', function(dropEvent) {
    dropEvent.preventDefault();
    _.each(dropEvent.originalEvent.dataTransfer.files, function(file) {
        var reader = new FileReader();
        var pos = 0;
        var startTime = +new Date();

        var hashObj = new sjcl.hash.sha256();

        reader.onprogress = function(progress) {
            var chunk = new Uint8Array(reader.result).subarray(pos, progress.loaded);
            hashObj.update(chunk);
            pos = progress.loaded;

            if(progress.lengthComputable) {
                console.log((progress.loaded/progress.total*100).toFixed(1)+'%');
            }
        };

        reader.onload = function() {
            var endTime = +new Date();
            console.log('hashed',file.name,'in',endTime-startTime,'ms');
            var chunk = new Uint8Array(reader.result, pos);
            if(chunk.length > 0) hashObj.update(chunk);
            console.log(sjcl.codec.hex.fromBits(hashObj.finalize()));
        };

        reader.readAsArrayBuffer(file);
    });
});

修改:根据SparkMD5发现了this answer。对于相同的8 MB文件,初始测试使其在一秒钟内运行,但它仍然比我想要的慢。

2 个答案:

答案 0 :(得分:3)

xxHash提供32位哈希值。它似乎比SparkMD5快约30%。但是,它似乎不适用于HTML5的ArrayBuffer,因此必须将文件作为文本读取。

var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
var chunkSize = 1024 * 1024 * 2;

$(document).on('drop', function (dropEvent) {
    dropEvent.preventDefault();

    _.each(dropEvent.originalEvent.dataTransfer.files, function (file) {
        var startTime = +new Date(), elapsed;
        var chunks = Math.ceil(file.size / chunkSize);
        var currentChunk = 0;
        var xxh = XXH();
        var fileReader = new FileReader();

        var readNextChunk = function() {
            var start = currentChunk * chunkSize;
            var end = Math.min(start + chunkSize, file.size);

            fileReader.readAsText(blobSlice.call(file, start, end));
        };

        fileReader.onload = function (e) {
            console.log("read chunk nr", currentChunk + 1, "of", chunks);
            xxh.update(e.target.result);
            ++currentChunk;

            if (currentChunk < chunks) {
                readNextChunk();
            } else {
                elapsed = +new Date() - startTime;
                console.info("computed hash", xxh.digest().toString(16), 'for file', file.name, 'in', elapsed, 'ms');
            }
        };

        fileReader.onerror = function () {
            console.warn("oops, something went wrong.");
        };

        readNextChunk();
    });
});

认为 blobSlice会复制该文件,我不是非常热衷于此。我也不特别喜欢将二进制数据视为文本。我通过挖掘xxHash的来源创建了与ArrayBuffer API一起使用的替代版本 - 结果只缺少一种方法,使HTML5's Uint8ArrayNode.js Buffer一样工作

/**
 * Hack to make Uint8Array work like a Node.js Buffer
 *
 * @param {Buffer} targetBuffer Buffer to copy into
 * @param {Number} targetStart Optional, Default: 0
 * @param {Number} sourceStart Optional, Default: 0
 * @param {Number} sourceEnd Optional, Default: source length
 * @see http://nodejs.org/api/buffer.html#buffer_buf_copy_targetbuffer_targetstart_sourcestart_sourceend
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Uint32Array
 */
Uint8Array.prototype.copy = function(targetBuffer, targetStart, sourceStart, sourceEnd) {
    targetStart = targetStart || 0;
    sourceStart = sourceStart || 0;
    sourceEnd = sourceEnd || this.length;
    for(var i=sourceStart; i<sourceEnd; ++i) {
        targetBuffer[targetStart+i] = this[i];
    }
};

$(document).on('drop', function(dropEvent) {
    dropEvent.preventDefault();
    _.each(dropEvent.originalEvent.dataTransfer.files, function(file) {
        var reader = new FileReader();
        var pos = 0;
        var startTime = +new Date();
        var xxh = XXH();

        reader.onprogress = function(progress) {
            var length = progress.loaded - pos;
            var arr = new Uint8Array(reader.result, pos, length);
            pos += length;

            xxh.update(arr);

            if(progress.lengthComputable) {
                console.log((progress.loaded/progress.total*100).toFixed(1)+'%');
            }
        };

        reader.onload = function() {
            var arr = new Uint8Array(reader.result, pos);
            xxh.update(arr);

            var elapsed = +new Date() - startTime;
            console.info("computed hash", xxh.digest().toString(16), 'for file', file.name, 'in', elapsed, 'ms');
        };

        reader.readAsArrayBuffer(file);
    });
});

不幸的是,它们在速度方面几乎完全相同,而且它仍在复制。但是,它在原始的8 MB文件上运行大约270毫秒,远远好于15秒。

答案 1 :(得分:2)

SparkMD5的速度要快得多:

var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
var chunkSize = 1024 * 1024 * 2;

$(document).on('drop', function (dropEvent) {
    dropEvent.preventDefault();

    _.each(dropEvent.originalEvent.dataTransfer.files, function (file) {
        var startTime = +new Date(), elapsed;
        var chunks = Math.ceil(file.size / chunkSize);
        var currentChunk = 0;
        var spark = new SparkMD5.ArrayBuffer();
        var fileReader = new FileReader();

        var readNextChunk = function() {
            var start = currentChunk * chunkSize;
            var end = Math.min(start + chunkSize, file.size);

            fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
        };

        fileReader.onload = function (e) {
            console.log("read chunk nr", currentChunk + 1, "of", chunks);
            spark.append(e.target.result);                 // append array buffer
            ++currentChunk;

            if (currentChunk < chunks) {
                readNextChunk();
            } else {
                elapsed = +new Date() - startTime;
                console.info("computed hash", spark.end(), 'for file', file.name, 'in', elapsed, 'ms'); // compute hash
            }
        };

        fileReader.onerror = function () {
            console.warn("oops, something went wrong.");
        };

        readNextChunk();
    });
});