1

We have need for faster price calculations in our app. Currently we iterate over product items in JS and calculate each product item’s price. I was thinking maybe native modules could be used for faster speeds. But it doesn’t seem like it?

When I test a simple C++ native module with performance.now() its slower than the JS equivalent. Its just a for loop of 20 iterations of a multiplication.

I guess there is some kind of overhead (JSON parsing?) when using native modules.

First I tried using the promise based RCT_EXPORT_METHOD way and the first execution would take about 15ms.

Then I tried RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD but it was still slower than JS. It took about 0.4ms first execution.

JS would take about 0.0025ms first execution.

Is native modules for just iterating and calculating prices a bad idea/will it not be faster than JS?

The code:

  int multiply(float a, float b)
  {
    for (int i = 0; i < 100; i++)
    {
      int test = a * b;
    }

    return a * b;
  }
  // Native module
  React.useEffect(() => {
    const p1 = performance.now();
    const test = multiply(3, 7);
    const p2 = performance.now();
    const result = p2 - p1;
    console.log(`A: ${result}`, test);
  }, []);

  // JS
  React.useEffect(() => {
    const p1 = performance.now();
    const test = 3 * 7;
    for (let i = 0; i < 20; i++) {
      const a = 3 * 7;
    }
    const p2 = performance.now();
    const result = p2 - p1;
    console.log(`B: ${result}`, test);
  }, []);

Jesper Johansson
  • 599
  • 3
  • 14
  • It's an interesting question, and I don't know the answer, but can you include more about your original issue? Have you identified what takes too long in your current code? My guess is that multiplication is not where you're losing time, it's probably a network request, re-rendering issue, etc. Is 20 a good sample size for your app? Doing 20 math operations is extremely cheap in any language. – Abe Feb 06 '22 at 18:19

0 Answers0