summaryrefslogtreecommitdiff
path: root/benchmark/buffers/buffer-swap.js
diff options
context:
space:
mode:
authorJames M Snell <jasnell@gmail.com>2016-03-15 11:08:32 -0700
committerJames M Snell <jasnell@gmail.com>2016-03-23 08:52:44 -0700
commit7d73e60f60e2161457ca4c923008c9064a36bced (patch)
tree3fca1081a347bdc49ec710b971225d8f6a0c295b /benchmark/buffers/buffer-swap.js
parent443c2d5442edf78a5b91ed13e756e21ea30a5bb1 (diff)
downloadandroid-node-v8-7d73e60f60e2161457ca4c923008c9064a36bced.tar.gz
android-node-v8-7d73e60f60e2161457ca4c923008c9064a36bced.tar.bz2
android-node-v8-7d73e60f60e2161457ca4c923008c9064a36bced.zip
buffer: add swap16() and swap32() methods
Adds Buffer.prototype.swap16() and Buffer.prototype.swap32() methods that mutate the Buffer instance in-place by swapping the 16-bit and 32-bit byte-order. Example: ```js const buf = Buffer([0x1, 0x2, 0x3, 0x4]); buf.swap16(); console.log(buf); // prints Buffer(0x2, 0x1, 0x4, 0x3); buf.swap32(); console.log(buf); // prints Buffer(0x3, 0x4, 0x1, 0x2); ``` PR-URL: https://github.com/nodejs/node/pull/5724 Reviewed-By: Trevor Norris <trev.norris@gmail.com>
Diffstat (limited to 'benchmark/buffers/buffer-swap.js')
-rw-r--r--benchmark/buffers/buffer-swap.js61
1 files changed, 61 insertions, 0 deletions
diff --git a/benchmark/buffers/buffer-swap.js b/benchmark/buffers/buffer-swap.js
new file mode 100644
index 0000000000..4ff9a23d41
--- /dev/null
+++ b/benchmark/buffers/buffer-swap.js
@@ -0,0 +1,61 @@
+'use strict';
+
+const common = require('../common.js');
+
+const bench = common.createBenchmark(main, {
+ method: ['swap16', 'swap32', 'htons', 'htonl'],
+ len: [4, 64, 512, 768, 1024, 1536, 2056, 4096, 8192],
+ n: [1e6]
+});
+
+// The htons and htonl methods below are used to benchmark the
+// performance difference between doing the byteswap in pure
+// javascript regardless of Buffer size as opposed to dropping
+// down to the native layer for larger Buffer sizes.
+
+Buffer.prototype.htons = function htons() {
+ if (this.length % 2 !== 0)
+ throw new RangeError();
+ for (var i = 0, n = 0; i < this.length; i += 2) {
+ n = this[i];
+ this[i] = this[i + 1];
+ this[i + 1] = n;
+ }
+ return this;
+};
+
+Buffer.prototype.htonl = function htonl() {
+ if (this.length % 2 !== 0)
+ throw new RangeError();
+ for (var i = 0, n = 0; i < this.length; i += 4) {
+ n = this[i];
+ this[i] = this[i + 3];
+ this[i + 3] = n;
+ n = this[i + 1];
+ this[i + 1] = this[i + 2];
+ this[i + 2] = n;
+ }
+ return this;
+};
+
+function createBuffer(len) {
+ const buf = Buffer.allocUnsafe(len);
+ for (var i = 1; i <= len; i++)
+ buf[i - 1] = i;
+ return buf;
+}
+
+function bufferSwap(n, buf, method) {
+ for (var i = 1; i <= n; i++)
+ buf[method]();
+}
+
+function main(conf) {
+ const method = conf.method;
+ const len = conf.len | 0;
+ const n = conf.n | 0;
+ const buf = createBuffer(len);
+ bench.start();
+ bufferSwap(n, buf, method);
+ bench.end(n);
+}