Skip to content

Commit 1616895

Browse files
committed
Speed up decode by getting rid of indexOf
indexOf is O(n) (n=64 in this case) and has a lot of overhead [*] Instead of doing indexOf over and over use a lookup table [*] https://github.com/v8/v8/blob/master/src/js/string.js#L102-L115
1 parent 0647207 commit 1616895

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

lib/base64-arraybuffer.js

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,17 @@
55
* Copyright (c) 2012 Niklas von Hertzen
66
* Licensed under the MIT license.
77
*/
8-
(function(chars){
8+
(function(){
99
"use strict";
1010

11+
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
12+
13+
// Use a lookup table to find the index.
14+
var lookup = new Uint8Array(256);
15+
for (var i = 0; i < chars.length; i++) {
16+
lookup[chars.charCodeAt(i)] = i;
17+
}
18+
1119
exports.encode = function(arraybuffer) {
1220
var bytes = new Uint8Array(arraybuffer),
1321
i, len = bytes.length, base64 = "";
@@ -44,10 +52,10 @@
4452
bytes = new Uint8Array(arraybuffer);
4553

4654
for (i = 0; i < len; i+=4) {
47-
encoded1 = chars.indexOf(base64[i]);
48-
encoded2 = chars.indexOf(base64[i+1]);
49-
encoded3 = chars.indexOf(base64[i+2]);
50-
encoded4 = chars.indexOf(base64[i+3]);
55+
encoded1 = lookup[base64.charCodeAt(i)];
56+
encoded2 = lookup[base64.charCodeAt(i+1)];
57+
encoded3 = lookup[base64.charCodeAt(i+2)];
58+
encoded4 = lookup[base64.charCodeAt(i+3)];
5159

5260
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
5361
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
@@ -56,4 +64,4 @@
5664

5765
return arraybuffer;
5866
};
59-
})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
67+
})();

0 commit comments

Comments
 (0)