From 5b83012d1a684cb915c71b648dc5bb2324e5a334 Mon Sep 17 00:00:00 2001 From: Lovell Fuller Date: Tue, 21 Mar 2017 14:55:57 +0000 Subject: [PATCH] Wrap try/catch with function to allow V8 to optimise onclosetag Improves performance of this 'hot' function by ~20% Improves overall XML to JS conversion throughput by ~2% --- lib/parser.js | 19 +++++++++++-------- src/parser.coffee | 11 +++++++---- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/lib/parser.js b/lib/parser.js index fbb961dc..e72578a5 100644 --- a/lib/parser.js +++ b/lib/parser.js @@ -1,4 +1,4 @@ -// Generated by CoffeeScript 1.11.1 +// Generated by CoffeeScript 1.12.4 (function() { "use strict"; var bom, defaults, events, isEmpty, processItem, processors, sax, setImmediate, @@ -170,7 +170,7 @@ })(this); this.saxParser.onclosetag = (function(_this) { return function() { - var cdata, emptyStr, err, key, node, nodeName, obj, objClone, old, s, xpath; + var cdata, emptyStr, key, node, nodeName, obj, objClone, old, s, xpath; obj = stack.pop(); nodeName = obj["#name"]; if (!_this.options.explicitChildren || !_this.options.preserveChildrenOrder) { @@ -209,12 +209,15 @@ } return results; })()).concat(nodeName).join("/"); - try { - obj = _this.options.validator(xpath, s && s[nodeName], obj); - } catch (error1) { - err = error1; - _this.emit("error", err); - } + (function() { + var err; + try { + return obj = _this.options.validator(xpath, s && s[nodeName], obj); + } catch (error1) { + err = error1; + return _this.emit("error", err); + } + })(); } if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === 'object') { if (!_this.options.preserveChildrenOrder) { diff --git a/src/parser.coffee b/src/parser.coffee index 8673ec3f..8a375197 100644 --- a/src/parser.coffee +++ b/src/parser.coffee @@ -149,10 +149,13 @@ class exports.Parser extends events.EventEmitter if @options.validator? xpath = "/" + (node["#name"] for node in stack).concat(nodeName).join("/") - try - obj = @options.validator(xpath, s and s[nodeName], obj) - catch err - @emit "error", err + # Wrap try/catch with an inner function to allow V8 to optimise the containing function + # See https://github.com/Leonidas-from-XIV/node-xml2js/pull/369 + do => + try + obj = @options.validator(xpath, s and s[nodeName], obj) + catch err + @emit "error", err # put children into property and unfold chars if necessary if @options.explicitChildren and not @options.mergeAttrs and typeof obj is 'object'