From b3b5a0ca7466f76e9139f2f9409d5af4f42ea3f7 Mon Sep 17 00:00:00 2001 From: Joe Bateson Date: Thu, 24 Oct 2019 18:39:18 -0700 Subject: [PATCH] Cache getLocalAddress() to avoid per-request network address lookup (#454) --- packages/zipkin/src/InetAddress.js | 9 +++++++-- packages/zipkin/test/InetAddress.test.js | 4 ++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/zipkin/src/InetAddress.js b/packages/zipkin/src/InetAddress.js index e52b7990..b332d6dd 100644 --- a/packages/zipkin/src/InetAddress.js +++ b/packages/zipkin/src/InetAddress.js @@ -31,7 +31,7 @@ class InetAddress { } // In non-node environments we fallback to 127.0.0.1 -InetAddress.getLocalAddress = function getLocalAddress() { +function getLocalAddress() { const isNode = typeof process === 'object' && typeof process.on === 'function'; if (!isNode) { return new InetAddress('127.0.0.1'); @@ -40,6 +40,11 @@ InetAddress.getLocalAddress = function getLocalAddress() { // eslint-disable-next-line global-require const networkAddress = require('./network'); return new InetAddress(networkAddress.ipv4()); -}; +} + +// Cache this value at import time so as to avoid network interface +// lookup on every call +const cachedLocalAddress = getLocalAddress(); +InetAddress.getLocalAddress = () => cachedLocalAddress; module.exports = InetAddress; diff --git a/packages/zipkin/test/InetAddress.test.js b/packages/zipkin/test/InetAddress.test.js index 67a3bd1c..6f27195d 100644 --- a/packages/zipkin/test/InetAddress.test.js +++ b/packages/zipkin/test/InetAddress.test.js @@ -5,6 +5,10 @@ describe('InetAddress', () => { InetAddress.getLocalAddress(); }); + it('should return the same object reference for multiple calls (cached)', () => { + expect(InetAddress.getLocalAddress()).to.equal(InetAddress.getLocalAddress()); + }); + it('should convert an IP address to integer representation', () => { const addr = new InetAddress('80.91.37.133'); expect(addr.toInt()).to.equal(1348150661);