Description
This is more of a question about the internals of typescript. For some reason I ended up with a Node
object which had no parent. I'm pretty sure this is due to the way I configured the compiler using the API but this led me to the following function in the typescript source:
function getSourceFileOfNode(node) {
while (node && node.kind !== 256 /* SourceFile */) {
node = node.parent;
}
return node;
}
This function is eventually called when I use
NodeObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
};
getStart
has all optional parameters and I never pass in the sourceFile so getSourceFileOfNode
is always triggered.
Question:
Is there a reason why a node object doesn't have a reference to the source file object to which it belongs? We already store its kind
, parent
and other information, why not a reference to the sourceFile?
I know machines are fast, but going up the tree up to the source file every time we need to see the start of a node seems inefficient. Things could be faster especially for cases in which we have a tree with many levels. As an example consider this project: https://github.com/buzinas/tslint-eslint-rules
I've been writing a few rules here and I decided to check out just how many times the function gets called during the build process:
var count = 0;
var calls = 0;
function getSourceFileOfNode(node) {
calls ++;
while (node && node.kind !== 256 /* SourceFile */) {
count++;
node = node.parent;
}
console.log('count: ', [calls, count]);
return node;
}
I modified the function to print out the number of calls to the function and the number of times we go up in the tree, the result:
count: [ 19505, 78762 ]
So instead of accessing the source file 19505 times we have to execute 59,257 more checks and assignments. Would it decrease the efficiency of typescript if we were to add a reference to source file?