From 5549ad02829ffdfc035e75e511017fbb3f41f197 Mon Sep 17 00:00:00 2001 From: Andrey Lushnikov Date: Mon, 24 Jul 2017 21:43:54 -0700 Subject: [PATCH] Do not serialize remote objects unless needed This patch stops serializing console API arguments unless there are listeners of the 'console' event in puppeteer. This saves quite a lot CPU cycles. Fixes #117. --- lib/Page.js | 4 ++++ lib/helper.js | 22 ++++++++++++++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/lib/Page.js b/lib/Page.js index 2e41da22e4e..674360c15b3 100644 --- a/lib/Page.js +++ b/lib/Page.js @@ -232,6 +232,10 @@ class Page extends EventEmitter { } return; } + if (!this.listenerCount(Page.Events.Console)) { + event.args.map(arg => helper.releaseObject(this._client, arg)); + return; + } let values = await Promise.all(event.args.map(arg => helper.serializeRemoteObject(this._client, arg))); this.emit(Page.Events.Console, ...values); } diff --git a/lib/helper.js b/lib/helper.js index 364f0a5c4e1..339778bc190 100644 --- a/lib/helper.js +++ b/lib/helper.js @@ -45,7 +45,7 @@ class Helper { /** * @param {!Connection} client * @param {!Object} remoteObject - * @return {!Object} + * @return {!Promise} */ static async serializeRemoteObject(client, remoteObject) { if (remoteObject.unserializableValue) { @@ -75,9 +75,23 @@ class Helper { // Return description for unserializable object, e.g. 'window'. return remoteObject.description; } finally { - client.send('Runtime.releaseObject', {objectId: remoteObject.objectId}).catch(e => { - // While we were serializing object, the page might've navigated. - }); + Helper.releaseObject(client, remoteObject); + } + } + + /** + * @param {!Connection} client + * @param {!Object} remoteObject + * @return {!Promise} + */ + static async releaseObject(client, remoteObject) { + if (!remoteObject.objectId) + return; + try { + await client.send('Runtime.releaseObject', {objectId: remoteObject.objectId}); + } catch (e) { + // Exceptions might happen in case of a page been navigated or closed. + // Swallow these since they are harmless and we don't leak anything in this case. } }