Advertisement
rgruber

binary_search ipv4

Jun 1st, 2025
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (async function ipv4Benchmark() {
  2.   function ipToInt(ip) {
  3.     return ip.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0) >>> 0;
  4.   }
  5.  
  6.   function intToIp(int) {
  7.     return [24, 16, 8, 0].map(shift => (int >>> shift) & 255).join('.');
  8.   }
  9.  
  10.   function generateRandomIP() {
  11.     return Array(4).fill(0).map(() => Math.floor(Math.random() * 256)).join('.');
  12.   }
  13.  
  14.   function binarySearch(arr, val) {
  15.     let low = 0, high = arr.length - 1;
  16.     while (low <= high) {
  17.       const mid = (low + high) >>> 1;
  18.       const midVal = arr[mid];
  19.       if (midVal === val) return true;
  20.       else if (midVal < val) low = mid + 1;
  21.       else high = mid - 1;
  22.     }
  23.     return false;
  24.   }
  25.  
  26.   const log = console.log;
  27.   const ipCount = 5_000_000;
  28.   const checkCount = 1_000_000;
  29.  
  30.   log("Generating ip list");
  31.   const startGen = performance.now();
  32.  
  33.   const ipSet = new Set();
  34.   while (ipSet.size < ipCount) {
  35.     ipSet.add(ipToInt(generateRandomIP()));
  36.     if (ipSet.size % 100_000 === 0) log(`...${ipSet.size} done`);
  37.   }
  38.  
  39.   const ipArray = new Uint32Array([...ipSet].sort((a, b) => a - b));
  40.   const genTime = (performance.now() - startGen).toFixed(1);
  41.   log(`Generated sorted IPs in ${genTime} ms`);
  42.  
  43.   log("Generating test IPs (50% hits, 50% likely misses)...");
  44.   const testIPs = [];
  45.   for (let i = 0; i < checkCount / 2; i++) {
  46.     testIPs.push(ipArray[Math.floor(Math.random() * ipArray.length)]);
  47.   }
  48.   for (let i = 0; i < checkCount / 2; i++) {
  49.     testIPs.push(ipToInt(generateRandomIP()));
  50.   }
  51.   testIPs.sort(() => Math.random() - 0.5);
  52.  
  53.   log("Starting binary searches...");
  54.   await new Promise(r => setTimeout(r, 100)); // allow rendering if needed
  55.  
  56.   const startSearch = performance.now();
  57.   let found = 0;
  58.   for (let ip of testIPs) {
  59.     if (binarySearch(ipArray, ip)) found++;
  60.   }
  61.   const searchTime = (performance.now() - startSearch).toFixed(1);
  62.  
  63.   log(`Search complete in ${searchTime} ms`);
  64.   log(`Found: ${found} / ${checkCount}`);
  65. })();
Tags: BinarySearch
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement