From 47002da15e6047827729e312fd7c5c29745b8679 Mon Sep 17 00:00:00 2001 From: Sergey Tatarintsev Date: Wed, 14 Mar 2018 17:59:02 +0100 Subject: [PATCH] Memoize stats.toJson() In our tests we found out that on each request passing through dev middleware almost 3s spent in stats.toJson call even when stats have not changed between request. I've optimized this situation by memozing toJson result and using cached value unless stats change. --- helpers.js | 12 ++++++++++++ middleware.js | 3 ++- test/helpers-test.js | 21 +++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/helpers.js b/helpers.js index cfadd37..c2ae11f 100644 --- a/helpers.js +++ b/helpers.js @@ -7,3 +7,15 @@ exports.pathMatch = function(url, path) { return false; } } + +exports.createMemoizedToJson = function() { + var lastStats = null; + var lastJson = null; + return function(stats) { + if (lastStats !== stats) { + lastStats = stats; + lastJson = stats.toJson({ errorDetails: false }); + } + return lastJson; + } +}; diff --git a/middleware.js b/middleware.js index 644ea53..a697169 100644 --- a/middleware.js +++ b/middleware.js @@ -2,6 +2,7 @@ module.exports = webpackHotMiddleware; var helpers = require('./helpers'); var pathMatch = helpers.pathMatch; +var statsToJson = helpers.createMemoizedToJson(); function webpackHotMiddleware(compiler, opts) { opts = opts || {}; @@ -84,7 +85,7 @@ function createEventStream(heartbeat) { function publishStats(action, statsResult, eventStream, log) { // For multi-compiler, stats will be an object with a 'children' array of stats - var bundles = extractBundles(statsResult.toJson({ errorDetails: false })); + var bundles = extractBundles(statsToJson(statsResult)); bundles.forEach(function(stats) { if (log) { log("webpack built " + (stats.name ? stats.name + " " : "") + diff --git a/test/helpers-test.js b/test/helpers-test.js index 4d5ae80..03ccedd 100644 --- a/test/helpers-test.js +++ b/test/helpers-test.js @@ -19,4 +19,25 @@ describe("helpers", function() { assert.equal(pathMatch("/path-and", "/path"), false); }); }); + + describe("createMemoizedToJson", function() { + var stats = function() { + return { + toJson: function() { + return {}; + } + } + }; + var toJson = null; + beforeEach(function() { + toJson = helpers.createMemoizedToJson(); + }); + it("should return same value for same stats instance", function() { + var instance = stats(); + assert.strictEqual(toJson(instance), toJson(instance)); + }); + it("should return same value for same stats instance", function() { + assert.notStrictEqual(toJson(stats()), toJson(stats())); + }); + }); });