From 155abfba182cc38ce90252a50c5af55640804783 Mon Sep 17 00:00:00 2001 From: Raymond Hill Date: Thu, 25 Apr 2019 18:36:03 -0400 Subject: [PATCH] Cache and reuse result of HNTrieRef.matches() when possible Due to how web pages typically load secondary resources and due to how HNTrieContainer instances are used in uBO, there is a great likelihood that the result of a previous call to HNTrieRef.matches() can be reused in a subsequent call. This has been confirmed by instrumenting HNTrieRef.matches(). Since uBO uses distinct HNTrieContainer instances to either match against the request or the origin hostnames, this means a high likelihood of repeated calls to HNTrieRef.matches() with the same hostname as argument, hence a performance gain when caching the argument+result -- as despite that HNTrie.matches() is fast, comparing two short strings is even faster if this allows to skip HNTrie.matches() altogether. --- src/js/hntrie.js | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/js/hntrie.js b/src/js/hntrie.js index 8b3dd18e09a90..323144a32133f 100644 --- a/src/js/hntrie.js +++ b/src/js/hntrie.js @@ -407,6 +407,8 @@ HNTrieContainer.prototype = { this.container = container; this.iroot = iroot; this.size = size; + this.last = -1; + this.needle = ''; }, //-------------------------------------------------------------------------- @@ -548,6 +550,8 @@ HNTrieContainer.prototype = { HNTrieContainer.prototype.HNTrieRef.prototype = { add: function(hn) { if ( this.container.setNeedle(hn).add(this.iroot) === 1 ) { + this.last = -1; + this.needle = ''; this.size += 1; return true; } @@ -555,6 +559,8 @@ HNTrieContainer.prototype.HNTrieRef.prototype = { }, addJS: function(hn) { if ( this.container.setNeedle(hn).addJS(this.iroot) === 1 ) { + this.last = -1; + this.needle = ''; this.size += 1; return true; } @@ -562,19 +568,33 @@ HNTrieContainer.prototype.HNTrieRef.prototype = { }, addWASM: function(hn) { if ( this.container.setNeedle(hn).addWASM(this.iroot) === 1 ) { + this.last = -1; + this.needle = ''; this.size += 1; return true; } return false; }, matches: function(needle) { - return this.container.setNeedle(needle).matches(this.iroot); + if ( needle !== this.needle ) { + this.needle = needle; + this.last = this.container.setNeedle(needle).matches(this.iroot); + } + return this.last; }, matchesJS: function(needle) { - return this.container.setNeedle(needle).matchesJS(this.iroot); + if ( needle !== this.needle ) { + this.needle = needle; + this.last = this.container.setNeedle(needle).matchesJS(this.iroot); + } + return this.last; }, matchesWASM: function(needle) { - return this.container.setNeedle(needle).matchesWASM(this.iroot); + if ( needle !== this.needle ) { + this.needle = needle; + this.last = this.container.setNeedle(needle).matchesWASM(this.iroot); + } + return this.last; }, [Symbol.iterator]: function() { return {