Created
March 10, 2013 21:07
-
-
Save mdakin/5130420 to your computer and use it in GitHub Desktop.
dart base64 perf test.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:math'; | |
var random = new Random(0xCAFEBABE); | |
/// The base64 encoding table | |
final List<int>characters = const [ | |
// A-Z [65-90] | |
65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, | |
// a-z [97-122] | |
97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, | |
// 0-9 [48-57] | |
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, | |
// + / = | |
43, 47, 61 | |
]; | |
_btoa(List<int> bytes, List<int> out, int j, int len) { | |
int a, b, c, b1, b2, b3, b4, i=0; | |
while (i < len) { | |
a = bytes[i++]; | |
b = bytes[i++]; | |
c = bytes[i++]; | |
b1 = (a >> 2) & 0x3F; | |
b2 = ((a & 0x3) << 4) | ((b >> 4) & 0xF); | |
b3 = ((b & 0xF) << 2) | ((c >> 6) & 0x3); | |
b4 = c & 0x3F; | |
if (len==3) | |
b!=0 ? c!=0 ? 0 : b4 = 64 : b3 = b4 = 64; | |
out[j++]=characters[b1]; | |
out[j++]=characters[b2]; | |
out[j++]=characters[b3]; | |
out[j++]=characters[b4]; | |
} | |
} | |
String btoa(List<int> bytes) { | |
var tailLen=bytes.length % 3, | |
bodyLen = bytes.length-tailLen, | |
array=new List<int>((bodyLen~/3)*4+(tailLen==0?0:4)); | |
_btoa(bytes, array, 0, bodyLen); | |
if (tailLen !=0) { | |
_btoa(<int>[bytes[bodyLen], tailLen==2?bytes[bodyLen+1]:0, 0], | |
array, (bodyLen~/3)*4, 3); | |
} | |
return new String.fromCharCodes(array); | |
} | |
fillRandom(List<int> l) { | |
for(int j=0; j < l.length; j+=2) { | |
l[j] = random.nextInt(255); | |
l[j+1]=0; | |
} | |
} | |
String encodeTest(List<int> l, int iterations) { | |
String enc; | |
for( int i = 0; i < iterations; ++i ) { | |
enc = btoa(l); | |
} | |
return enc; | |
} | |
void main() { | |
var l = new List<int>(1024); | |
var iterations = 20000; | |
fillRandom(l); | |
// Warm-up | |
String enc; | |
enc = encodeTest(l, 1000); | |
var w = new Stopwatch()..start(); | |
enc = encodeTest(l, iterations); | |
print("Encode for $iterations is ${w.elapsedMilliseconds} msec"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment