benchmarks.js (15774B) - View raw
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440/******************************************************************************* uBlock Origin - a comprehensive, efficient content blocker Copyright (C) 2014-present Raymond Hill This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see {http://www.gnu.org/licenses/}. Home: https://github.com/gorhill/uBlock */ import { domainFromHostname, entityFromDomain, hostnameFromURI, } from './uri-utils.js'; import { FilteringContext } from './filtering-context.js'; import { LineIterator } from './text-utils.js'; import cosmeticFilteringEngine from './cosmetic-filtering.js'; import io from './assets.js'; import scriptletFilteringEngine from './scriptlet-filtering.js'; import { sessionFirewall } from './filtering-engines.js'; import { default as sfne } from './static-net-filtering.js'; import webRequest from './traffic.js'; import µb from './background.js'; /******************************************************************************/ // The requests.json.gz file can be downloaded from: // https://cdn.cliqz.com/adblocking/requests_top500.json.gz // // Which is linked from: // https://whotracks.me/blog/adblockers_performance_study.html // // Copy the file into ./tmp/requests.json.gz // // If the file is present when you build uBO using `make-[target].sh` from // the shell, the resulting package will have `./assets/requests.json`, which // will be looked-up by the method below to launch a benchmark session. // // From uBO's dev console, launch the benchmark: // µBlock.staticNetFilteringEngine.benchmark(); // // The usual browser dev tools can be used to obtain useful profiling // data, i.e. start the profiler, call the benchmark method from the // console, then stop the profiler when it completes. // // Keep in mind that the measurements at the blog post above where obtained // with ONLY EasyList. The CPU reportedly used was: // https://www.cpubenchmark.net/cpu.php?cpu=Intel+Core+i7-6600U+%40+2.60GHz&id=2608 // // Rename ./tmp/requests.json.gz to something else if you no longer want // ./assets/requests.json in the build. const loadBenchmarkDataset = (( ) => { let datasetPromise; const ttlTimer = vAPI.defer.create(( ) => { datasetPromise = undefined; }); return async function() { ttlTimer.offon({ min: 2 }); if ( datasetPromise !== undefined ) { return datasetPromise; } const datasetURL = µb.hiddenSettings.benchmarkDatasetURL; if ( datasetURL === 'unset' ) { console.info(`No benchmark dataset available.`); return; } console.info(`Loading benchmark dataset...`); datasetPromise = io.fetchText(datasetURL).then(details => { console.info(`Parsing benchmark dataset...`); let requests = []; if ( details.content.startsWith('[') ) { try { requests = JSON.parse(details.content); } catch { } } else { const lineIter = new LineIterator(details.content); const parsed = []; while ( lineIter.eot() === false ) { const line = lineIter.next().trim(); if ( line === '' ) { continue; } try { parsed.push(JSON.parse(line)); } catch { parsed.length = 0; break; } } requests = parsed; } if ( requests.length === 0 ) { return; } const out = []; for ( const request of requests ) { if ( request instanceof Object === false ) { continue; } if ( !request.frameUrl || !request.url ) { continue; } if ( request.cpt === 'document' ) { request.cpt = 'main_frame'; } else if ( request.cpt === 'xhr' ) { request.cpt = 'xmlhttprequest'; } out.push(request); } return out; }).catch(details => { console.info(`Not found: ${details.url}`); datasetPromise = undefined; }); return datasetPromise; }; })(); /******************************************************************************/ export async function benchmarkStaticNetFiltering(options = {}) { const { target, redirectEngine } = options; const requests = await loadBenchmarkDataset(); if ( Array.isArray(requests) === false || requests.length === 0 ) { const text = 'No dataset found to benchmark'; console.info(text); return text; } console.info(`Benchmarking staticNetFilteringEngine.matchRequest()...`); const fctxt = new FilteringContext(); if ( typeof target === 'number' ) { const request = requests[target]; fctxt.setURL(request.url); fctxt.setDocOriginFromURL(request.frameUrl); fctxt.setType(request.cpt); const r = sfne.matchRequest(fctxt); console.info(`Result=${r}:`); console.info(`\ttype=${fctxt.type}`); console.info(`\turl=${fctxt.url}`); console.info(`\tdocOrigin=${fctxt.getDocOrigin()}`); if ( r !== 0 ) { console.info(sfne.toLogData()); } return; } const t0 = performance.now(); let matchCount = 0; let blockCount = 0; let allowCount = 0; let redirectCount = 0; let removeparamCount = 0; let urlskipCount = 0; let cspCount = 0; let permissionsCount = 0; let replaceCount = 0; for ( const request of requests ) { fctxt.setURL(request.url); if ( fctxt.getIPAddress() === '' ) { fctxt.setIPAddress('93.184.215.14\n2606:2800:21f:cb07:6820:80da:af6b:8b2c'); } fctxt.setDocOriginFromURL(request.frameUrl); fctxt.setType(request.cpt); sfne.redirectURL = undefined; const r = sfne.matchRequest(fctxt); matchCount += 1; if ( r === 1 ) { blockCount += 1; } else if ( r === 2 ) { allowCount += 1; } if ( r !== 1 ) { if ( sfne.transformURL(fctxt) ) { redirectCount += 1; } if ( sfne.hasQuery(fctxt) ) { if ( sfne.filterQuery(fctxt) ) { removeparamCount += 1; } } if ( sfne.urlSkip(fctxt, false) ) { urlskipCount += 1; } if ( fctxt.isDocument() ) { if ( sfne.matchAndFetchModifiers(fctxt, 'csp') ) { cspCount += 1; } if ( sfne.matchAndFetchModifiers(fctxt, 'permissions') ) { permissionsCount += 1; } } sfne.matchHeaders(fctxt, []); if ( sfne.matchAndFetchModifiers(fctxt, 'replace') ) { replaceCount += 1; } } else if ( redirectEngine !== undefined ) { if ( sfne.redirectRequest(redirectEngine, fctxt) ) { redirectCount += 1; } if ( fctxt.isRootDocument() && sfne.urlSkip(fctxt, true) ) { urlskipCount += 1; } } } const t1 = performance.now(); const dur = t1 - t0; const output = [ 'Benchmarked static network filtering engine:', `\tEvaluated ${matchCount} requests in ${dur.toFixed(0)} ms`, `\tAverage: ${(dur / matchCount).toFixed(3)} ms per request`, `\tNot blocked: ${matchCount - blockCount - allowCount}`, `\tBlocked: ${blockCount}`, `\tUnblocked: ${allowCount}`, `\tredirect=: ${redirectCount}`, `\tremoveparam=: ${removeparamCount}`, `\turlskip=: ${urlskipCount}`, `\tcsp=: ${cspCount}`, `\tpermissions=: ${permissionsCount}`, `\treplace=: ${replaceCount}`, ]; const s = output.join('\n'); console.info(s); return s; } /******************************************************************************/ export async function tokenHistogramsfunction() { const requests = await loadBenchmarkDataset(); if ( Array.isArray(requests) === false || requests.length === 0 ) { console.info('No requests found to benchmark'); return; } console.info(`Computing token histograms...`); const fctxt = new FilteringContext(); const missTokenMap = new Map(); const hitTokenMap = new Map(); const reTokens = /[0-9a-z%]{2,}/g; for ( let i = 0; i < requests.length; i++ ) { const request = requests[i]; fctxt.setURL(request.url); fctxt.setDocOriginFromURL(request.frameUrl); fctxt.setType(request.cpt); const r = sfne.matchRequest(fctxt); for ( let [ keyword ] of request.url.toLowerCase().matchAll(reTokens) ) { const token = keyword.slice(0, 7); if ( r === 0 ) { missTokenMap.set(token, (missTokenMap.get(token) || 0) + 1); } else if ( r === 1 ) { hitTokenMap.set(token, (hitTokenMap.get(token) || 0) + 1); } } } const customSort = (a, b) => b[1] - a[1]; const topmisses = Array.from(missTokenMap).sort(customSort).slice(0, 100); for ( const [ token ] of topmisses ) { hitTokenMap.delete(token); } const tophits = Array.from(hitTokenMap).sort(customSort).slice(0, 100); console.info('Misses:', JSON.stringify(topmisses)); console.info('Hits:', JSON.stringify(tophits)); } /******************************************************************************/ export async function benchmarkDynamicNetFiltering() { const requests = await loadBenchmarkDataset(); if ( Array.isArray(requests) === false || requests.length === 0 ) { console.info('No requests found to benchmark'); return; } console.info(`Benchmarking sessionFirewall.evaluateCellZY()...`); const fctxt = new FilteringContext(); const t0 = performance.now(); for ( const request of requests ) { fctxt.setURL(request.url); fctxt.setTabOriginFromURL(request.frameUrl); fctxt.setType(request.cpt); sessionFirewall.evaluateCellZY( fctxt.getTabHostname(), fctxt.getHostname(), fctxt.type ); } const t1 = performance.now(); const dur = t1 - t0; console.info(`Evaluated ${requests.length} requests in ${dur.toFixed(0)} ms`); console.info(`\tAverage: ${(dur / requests.length).toFixed(3)} ms per request`); } /******************************************************************************/ export async function benchmarkCosmeticFiltering() { const requests = await loadBenchmarkDataset(); if ( Array.isArray(requests) === false || requests.length === 0 ) { console.info('No requests found to benchmark'); return; } const output = [ 'Benchmarking cosmeticFilteringEngine.retrieveSpecificSelectors()...', ]; const details = { tabId: undefined, frameId: undefined, hostname: '', domain: '', }; const options = { noSpecificCosmeticFiltering: false, noGenericCosmeticFiltering: false, dontInject: true, }; let count = 0; const t0 = performance.now(); for ( let i = 0; i < requests.length; i++ ) { const request = requests[i]; if ( request.cpt !== 'main_frame' ) { continue; } count += 1; details.hostname = hostnameFromURI(request.url); details.domain = domainFromHostname(details.hostname); details.entity = entityFromDomain(details.domain); void cosmeticFilteringEngine.retrieveSpecificSelectors(details, options); } const t1 = performance.now(); const dur = t1 - t0; output.push( `Evaluated ${count} retrieval in ${dur.toFixed(0)} ms`, `\tAverage: ${(dur / count).toFixed(3)} ms per document` ); const s = output.join('\n'); console.info(s); return s; } /******************************************************************************/ export async function benchmarkScriptletFiltering() { const requests = await loadBenchmarkDataset(); if ( Array.isArray(requests) === false || requests.length === 0 ) { console.info('No requests found to benchmark'); return; } const output = [ 'Benchmarking scriptletFilteringEngine.retrieve()...', ]; const details = { domain: '', entity: '', hostname: '', tabId: 0, url: '', nocache: true, }; let count = 0; const t0 = performance.now(); for ( let i = 0; i < requests.length; i++ ) { const request = requests[i]; if ( request.cpt !== 'main_frame' ) { continue; } count += 1; details.url = request.url; details.hostname = hostnameFromURI(request.url); details.domain = domainFromHostname(details.hostname); details.entity = entityFromDomain(details.domain); void scriptletFilteringEngine.retrieve(details); } const t1 = performance.now(); const dur = t1 - t0; output.push( `Evaluated ${count} retrieval in ${dur.toFixed(0)} ms`, `\tAverage: ${(dur / count).toFixed(3)} ms per document` ); const s = output.join('\n'); console.info(s); return s; } /******************************************************************************/ export async function benchmarkOnBeforeRequest() { const requests = await loadBenchmarkDataset(); if ( Array.isArray(requests) === false || requests.length === 0 ) { console.info('No requests found to benchmark'); return; } const mappedTypes = new Map([ [ 'document', 'main_frame' ], [ 'subdocument', 'sub_frame' ], ]); console.info('webRequest.onBeforeRequest()...'); const t0 = self.performance.now(); const promises = []; const details = { documentUrl: '', tabId: -1, parentFrameId: -1, frameId: 0, type: '', url: '', }; for ( const request of requests ) { details.documentUrl = request.frameUrl; details.tabId = -1; details.parentFrameId = -1; details.frameId = 0; details.type = mappedTypes.get(request.cpt) || request.cpt; details.url = request.url; if ( details.type === 'main_frame' ) { continue; } promises.push(webRequest.onBeforeRequest(details)); } return Promise.all(promises).then(results => { let blockCount = 0; for ( const r of results ) { if ( r !== undefined ) { blockCount += 1; } } const t1 = self.performance.now(); const dur = t1 - t0; console.info(`Evaluated ${requests.length} requests in ${dur.toFixed(0)} ms`); console.info(`\tBlocked ${blockCount} requests`); console.info(`\tAverage: ${(dur / requests.length).toFixed(3)} ms per request`); }); } /******************************************************************************/