Fix access to "-1" property on nodesOut array. (#6582)

Similar to the fixes in https://github.com/babel/babel/pull/6580 and
https://github.com/babel/babel/pull/6581, accesses of the form

```js
nodesOut[nodesOut.length - 1]
```

where `nodesOut` can be an empty array, are bad for performance in Node.
In this particular case it's easy to restructure the code a bit to not
require the array access at all, but just track the current `tail` as we
go.

This is a non-breaking performance fix.
This commit is contained in:
Benedikt Meurer 2017-10-29 02:16:04 +02:00 committed by Henry Zhu
parent 962128c0f0
commit 5baa36109e

View File

@ -519,20 +519,17 @@ export default function({ types: t }) {
}
}
let tail = null;
const nodesOut = [];
for (const node of nodes) {
const tail = nodesOut[nodesOut.length - 1];
if (
tail &&
t.isVariableDeclaration(tail) &&
t.isVariableDeclaration(node)
) {
if (tail !== null && t.isVariableDeclaration(node)) {
// Create a single compound declarations
tail.declarations.push(...node.declarations);
} else {
// Make sure the original node kind is used for each compound declaration
node.kind = nodeKind;
nodesOut.push(node);
tail = t.isVariableDeclaration(node) ? node : null;
}
}