goodeggs/fibrous — pull request #29 by bobzoller (2014-08-07 14:45:25+00:00)
Title: fibrous-wrapped functions report correct arity

In the first version of fibrous, all wrapped functions returned an arity (length) of 0. After [a176ab7](https://github.com/goodeggs/fibrous/commit/a176ab7), we returned an arity of 1, to achieve compatibility with naive libraries that used a `fn.length > 0` check to determine asynchronicity.

Now, using a bit of `eval`, fibrous wrapped functions will return their correct arity, (original length + 1, to account for the fibrous-managed callback parameter).

I'll argue this use of eval is OK. We're not executing any user code. The performance hit, while comparatively large (2x, see below) to the previous version, only takes ~100ms to instrument 10,000 functions.

Here's the benchmark script I used:

```coffee
fibrous = require './lib/fibrous'

COUNT = process.env.COUNT

startHeap = process.memoryUsage().heapUsed
startTime = Date.now()

fns = []

for [1..COUNT]
fns.push fibrous(->
a = 1
b = 2
a + b is 3 or throw new Error('wtf')
)

global.gc()

endHeap = process.memoryUsage().heapUsed
endTime = Date.now()

console.log "after #{COUNT} fibrous wrappers, heapUsed start: #{startHeap}, end: #{endHeap}, delta: #{endHeap - startHeap} ... took #{endTime - startTime}ms"
```

the before runs:

```bash
$ for ((n=0;n<5;n++)); do COUNT=10000 coffee --nodejs '--expose-gc' test.coffee; done
after 10000 fibrous wrappers, heapUsed start: 6926808, end: 13701776, delta: 6774968 ... took 61ms
after 10000 fibrous wrappers, heapUsed start: 5821536, end: 14025088, delta: 8203552 ... took 56ms
after 10000 fibrous wrappers, heapUsed start: 6923912, end: 13699912, delta: 6776000 ... took 63ms
after 10000 fibrous wrappers, heapUsed start: 6923528, end: 13700312, delta: 6776784 ... took 64ms
after 10000 fibrous wrappers, heapUsed start: 6924248, end: 13698544, delta: 6774296 ... took 62ms
```

and after:

```bash
$ for ((n=0;n<5;n++)); do COUNT=10000 coffee --nodejs '--expose-gc' test.coffee; done
after 10000 fibrous wrappers, heapUsed start: 6927624, end: 15482840, delta: 8555216 ... took 108ms
after 10000 fibrous wrappers, heapUsed start: 6930024, end: 15483832, delta: 8553808 ... took 111ms
after 10000 fibrous wrappers, heapUsed start: 6927648, end: 15482264, delta: 8554616 ... took 113ms
after 10000 fibrous wrappers, heapUsed start: 6928344, end: 15482128, delta: 8553784 ... took 109ms
after 10000 fibrous wrappers, heapUsed start: 6927608, end: 15482856, delta: 8555248 ... took 105ms
```

Thoughts?