etienne-martin/device-detector-js

Performance issue

kostia1st opened this issue · 3 comments

Here's a sample code:

  const deviceDetector = new DeviceDetector();
  const startPoint = performance.now();
  deviceDetector.parse('');
  console.log(`Time elapsed #1: ${Math.trunc(performance.now() - startPoint)}ms`);
  deviceDetector.parse('');
  console.log(`Time elapsed #2: ${Math.trunc(performance.now() - startPoint)}ms`);
  deviceDetector.parse('');
  console.log(`Time elapsed #3: ${Math.trunc(performance.now() - startPoint)}ms`);

Here's the result:

Time elapsed #1: 287ms
Time elapsed #2: 511ms
Time elapsed #3: 514ms

So, I see here a few issues:

  • second run takes almost as much time as the first one, but starting with third everything starts to work faster; given there's some kind of lazy cache, I'd expect the second run already be fast;
  • overall question - is it OK that a fully locally loaded library takes ~280ms of CPU time to process a simple input string? For the context, I run it on AMD Ryzen 7 5800HS - which is a relatively capable CPU

After looking into profiler, it looks like the entire time is basically taken by running Regexps (some individual ones run for tens of ms!)

chrome_tBjtOfAQHG
Looks like those MobileParser regexps rock big time.

I'm not into the lib's code yet, but my take is that this could have a major performance improvement.

UPD: Seems like it's rather about initializing RegExp objects. If so, there's little could be done about it I guess.
However, it still isn't clear why it takes 2 attempts to parse in order to create a usable internal cache.

you have the wrong measurement.

  const deviceDetector = new DeviceDetector();
  let startPoint = performance.now();
  deviceDetector.parse('');
  console.log(`Time elapsed #1: ${Math.trunc(performance.now() - startPoint)}ms`);
  startPoint = performance.now();
  deviceDetector.parse('');
  console.log(`Time elapsed #2: ${Math.trunc(performance.now() - startPoint)}ms`);
  deviceDetector.parse('');
  startPoint = performance.now();
  console.log(`Time elapsed #3: ${Math.trunc(performance.now() - startPoint)}ms`);