Skip to content
Merged
Prev Previous commit
Next Next commit
minor 20% optimization to lookup
  • Loading branch information
mkruskal-google committed May 9, 2025
commit 7f1e3082d1c4d10ce3d71786c6b66ee2d235f993
30 changes: 21 additions & 9 deletions src/namespace.js
Original file line number Diff line number Diff line change
Expand Up @@ -404,26 +404,36 @@ Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChe
// Start at root if path is absolute
if (path[0] === "")
return this.root.lookup(path.slice(1), filterTypes);
var flatPath = path.join(".");

var found = this._lookupImpl(path);
var found = this._lookupImpl(path, flatPath);
if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {
return found;
}

// If there hasn't been a match, try again at the parent
if (this.parent === null || parentAlreadyChecked)
// If there hasn't been a match, walk up the tree
if (parentAlreadyChecked)
return null;
return this.parent.lookup(path, filterTypes);

var current = this;
while (current.parent) {
found = current.parent._lookupImpl(path, flatPath);
if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {
return found;
}
current = current.parent;
}
return null;
};

/**
* Internal helper for lookup that handles searching just at this namespace and below along with caching.
* @param {string[]} path Path to look up
* @param {string} flatPath Flattened version of the path to use as a cache key
* @returns {ReflectionObject|null} Looked up object or `null` if none could be found
* @private
*/
Namespace.prototype._lookupImpl = function lookup(path) {
var flatPath = path.join(".");
Namespace.prototype._lookupImpl = function lookup(path, flatPath) {
if(Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) {
return this._lookupCache[flatPath];
}
Expand All @@ -434,13 +444,15 @@ Namespace.prototype._lookupImpl = function lookup(path) {
if (found) {
if (path.length === 1) {
exact = found;
} else if (found instanceof Namespace && (found = found._lookupImpl(path.slice(1))))
exact = found;
} else if (found instanceof Namespace) {
path = path.slice(1);
exact = found._lookupImpl(path, path.join("."));
}

// Otherwise try each nested namespace
} else {
for (var i = 0; i < this.nestedArray.length; ++i)
if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path)))
if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath)))
exact = found;
}

Expand Down