From 72c55e711da29e41da660e804aa1247794ee43b5 Mon Sep 17 00:00:00 2001 From: Chris Pettitt Date: Tue, 9 Sep 2014 09:26:39 -0700 Subject: [PATCH] Performance improvements --- lib/graph.js | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/lib/graph.js b/lib/graph.js index bafc12b8..9e63edc6 100644 --- a/lib/graph.js +++ b/lib/graph.js @@ -35,13 +35,16 @@ function Graph(opts) { this._nodes = {}; // v -> edgeObj - this._in= {}; + this._in = {}; // v -> edgeObj - this._out= {}; + this._out = {}; + + // e -> edgeObj + this._edgeObjs = {}; // e -> attrs - this._edges = {}; + this._edgeAttrs = {}; } /* Number of nodes in the graph. Should only be changed by the implementation. */ @@ -131,7 +134,7 @@ Graph.prototype.edgeCount = function() { }; Graph.prototype.allEdges = function() { - return _.map(_.keys(this._edges), edgeIdToObj); + return _.values(this._edgeObjs); }; Graph.prototype.path = function() { @@ -150,7 +153,7 @@ Graph.prototype.edge = function(v, w, name) { var e = (arguments.length === 1 ? edgeObjToId(this.isDirected, arguments[0]) : edgeArgsToId(this.isDirected, v, w, name)); - var edge = this._edges[e]; + var edge = this._edgeAttrs[e]; if (edge) { return edge; } @@ -169,10 +172,13 @@ Graph.prototype.edge = function(v, w, name) { this.node(v); this.node(w); - edge = _.merge({}, this.edgeAttrDefs); - this._edges[e] = edge; - this._out[v][e] = true; - this._in[w][e] = true; + edge = this._edgeAttrs[e] = _.merge({}, this.edgeAttrDefs); + + var edgeObj = edgeIdToObj(e); + Object.freeze(edgeObj); + this._edgeObjs[e] = edgeObj; + this._out[v][e] = edgeObj; + this._in[w][e] = edgeObj; this._edgeCount++; return edge; } @@ -182,14 +188,14 @@ Graph.prototype.hasEdge = function(v, w, name) { var e = (arguments.length === 1 ? edgeObjToId(this.isDirected, arguments[0]) : edgeArgsToId(this.isDirected, v, w, name)); - return _.has(this._edges, e); + return _.has(this._edgeAttrs, e); }; Graph.prototype.removeEdge = function(v, w, name) { var e = (arguments.length === 1 ? edgeObjToId(this.isDirected, arguments[0]) : edgeArgsToId(this.isDirected, v, w, name)); - if (_.has(this._edges, e)) { + if (_.has(this._edgeAttrs, e)) { if (arguments.length === 1) { v = arguments[0].v; w = arguments[0].w; @@ -197,7 +203,8 @@ Graph.prototype.removeEdge = function(v, w, name) { } delete this._out[v][e]; delete this._in[w][e]; - delete this._edges[e]; + delete this._edgeAttrs[e]; + delete this._edgeObjs[e]; this._edgeCount--; } }; @@ -205,14 +212,14 @@ Graph.prototype.removeEdge = function(v, w, name) { Graph.prototype.inEdges = function(v) { var inV = this._in[v]; if (inV) { - return _.map(_.keys(inV), edgeIdToObj); + return _.values(inV); } }; Graph.prototype.outEdges = function(v) { var outV = this._out[v]; if (outV) { - return _.map(_.keys(outV), edgeIdToObj); + return _.values(outV); } };