console.time('#1');
b = Buffer.alloc(100);
for (var ctr = 0; ctr < b.length; ctr++) {
b[ctr] = 65;
}
console.timeEnd('#1');
TIME: 0.213ms
console.time('#2');
let result = '';
for (var ctr = 0; ctr < 100; ctr++) {
result += String.fromCharCode(65);
}
console.timeEnd('#2');
TIME: 0.121ms
I would have thought #1 -- the buffer change -- would have been faster. I'm really surprised and am wondering why appending to a string is faster?
ADDENDUM:
Removing Buffer.alloc from test.
b = Buffer.alloc(100);
console.time('#1');
for (var ctr = 0; ctr < b.length; ctr++) {
b[ctr] = 65;
}
console.timeEnd('#1');
TIME: 0.136ms
Removing .length from test and setting a hard 100.
b = Buffer.alloc(100);
console.time('#1b');
for (var ctr = 0; ctr < 100; ctr++) {
b[ctr] = 65;
}
console.timeEnd('#1b');
TIME: 0.117ms
console.time('#2');
let result = '';
for (var ctr = 0; ctr < 100; ctr++) {
result += String.fromCharCode(65);
}
console.timeEnd('#2');
TIME: 0.125ms
It seems that both adjusting "Buffer.alloc" (which was expected) and ".length" added to execution times. Interesting exercise.
b[ctr] = 'a';doesn't appear to work. You need to put an integer value in the buffer when accessing it that way.