'React Native - Native module vs JS performance

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);
  }, []);



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source