Commit 8c0347d8e7f88171cd4c45eec22b42c5c7332fac
Optimize `pull` sink callback and throw if the sink is called multiple times.
The check sets the copied arguments to `null` to minimize potential memory leaks. The `switch` is used to try to avoid a costly `unshift` + Array `apply`, to make the call slightly faster.Isiah Meadows authored on 7/8/2016, 3:54:14 AM
impinball committed on 7/8/2016, 7:20:43 AM
Parent: 680e32e19ee15c33b5ad2e19c94d765616f983ae
Files changed
pull.js | changed |
test/pull.js | changed |
pull.js | ||
---|---|---|
@@ -6,10 +6,27 @@ | ||
6 | 6 | var args = new Array(length) |
7 | 7 | for(var i = 0; i < length; i++) |
8 | 8 | args[i] = arguments[i] |
9 | 9 | return function (read) { |
10 | - args.unshift(read) | |
11 | - return pull.apply(null, args) | |
10 | + if (args == null) { | |
11 | + throw new TypeError("partial sink should only be called once!") | |
12 | + } | |
13 | + | |
14 | + // Grab the reference after the check, because it's always an array now | |
15 | + // (engines like that kind of consistency). | |
16 | + var ref = args | |
17 | + args = null | |
18 | + | |
19 | + // Prioritize common case of small number of pulls. | |
20 | + switch (length) { | |
21 | + case 1: return pull(read, ref[0]) | |
22 | + case 2: return pull(read, ref[0], ref[1]) | |
23 | + case 3: return pull(read, ref[0], ref[1], ref[2]) | |
24 | + case 4: return pull(read, ref[0], ref[1], ref[2], ref[3]) | |
25 | + default: | |
26 | + ref.unshift(read) | |
27 | + return pull.apply(null, ref) | |
28 | + } | |
12 | 29 | } |
13 | 30 | } |
14 | 31 | |
15 | 32 | var read = a |
@@ -29,9 +46,4 @@ | ||
29 | 46 | } |
30 | 47 | |
31 | 48 | return read |
32 | 49 | } |
33 | - | |
34 | - | |
35 | - | |
36 | - | |
37 | - |
test/pull.js | ||
---|---|---|
@@ -3,10 +3,9 @@ | ||
3 | 3 | function curry (fun) { |
4 | 4 | return function () { |
5 | 5 | var args = [].slice.call(arguments) |
6 | 6 | return function (read) { |
7 | - args.unshift(read) | |
8 | - return fun.apply(null, args) | |
7 | + return fun.apply(null, [read].concat(args)) | |
9 | 8 | } |
10 | 9 | } |
11 | 10 | } |
12 | 11 | |
@@ -94,4 +93,21 @@ | ||
94 | 93 | // }) |
95 | 94 | // ) |
96 | 95 | // |
97 | 96 | |
97 | +tape("writable pull() should throw when called twice", function (t) { | |
98 | + t.plan(2) | |
99 | + | |
100 | + var stream = pull( | |
101 | + map(function (e) { return e*e }), | |
102 | + sum(function (err, value) { | |
103 | + console.log(value) | |
104 | + t.equal(value, 385) | |
105 | + }) | |
106 | + ) | |
107 | + | |
108 | + stream(values([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) | |
109 | + | |
110 | + t.throws(function () { | |
111 | + stream(values([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) | |
112 | + }, TypeError) | |
113 | +}) |
Built with git-ssb-web