下面的代码对数组进行base64编码,但是每次循环都会产生一个string对象,当编码很大的文件时(如70M)时,就会产生70个base64对象,内存占用量从1,到70M,导致程序占用大量内存,且无法回收。最后程序崩溃;
-
var ENCODE_TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-
function arrayToBase64(array) {
-
var src = new Uint8Array(array);
-
var len = src.length;
-
var base64 = '';
-
var srcOff = 0;
-
while (len > 0) {
-
base64 += ENCODE_TABLE.charAt((src[srcOff] >> 2) & 0x3F);
-
if (len >= 3) {
-
base64 += ENCODE_TABLE.charAt(((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F));
-
base64 += ENCODE_TABLE.charAt(((src[srcOff + 1] << 2) & 0x3C) | ((src[srcOff + 2] >> 6) & 0x03));
-
base64 += ENCODE_TABLE.charAt(src[srcOff + 2] & 0x3F);
-
srcOff += 3;
-
len -= 3;
-
} else if (len == 2) {
-
base64 += ENCODE_TABLE.charAt(((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F));
-
base64 += ENCODE_TABLE.charAt((src[srcOff + 1] << 2) & 0x3C);
-
srcOff += 2;
-
len -= 2;
-
} else {
-
base64 += ENCODE_TABLE.charAt((src[srcOff] << 4) & 0x30);
-
len -= 1;
-
}
-
}
-
return base64;
-
}
阅读(1403) | 评论(0) | 转发(0) |