React Native - Native module vs JS performance - react-native

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

Related

OfflineAudioContext processing takes increasingly longer in Safari

I am processing an audio buffer with an OfflineAudioContext with the following node layout:
[AudioBufferSourceNode] -> [AnalyserNode] -> [OfflineAudioContext]
This works very good on Chrome (106.0.5249.119) but on Safari 16 (17614.1.25.9.10, 17614) each time I run the analysis takes longer and longer. Both running on macOS.
What's curious is that I must quit Safari to "reset" the processing time.
I guess there's a memory leak?
Is there anything that I'm doing wrong in the JavaScript code that would cause Safari to not garbage collect?
async function processFrequencyData(
audioBuffer,
options
) {
const {
fps,
numberOfSamples,
maxDecibels,
minDecibels,
smoothingTimeConstant,
} = options;
const frameFrequencies = [];
const oc = new OfflineAudioContext({
length: audioBuffer.length,
sampleRate: audioBuffer.sampleRate,
numberOfChannels: audioBuffer.numberOfChannels,
});
const lengthInMillis = 1000 * (audioBuffer.length / audioBuffer.sampleRate);
const source = new AudioBufferSourceNode(oc);
source.buffer = audioBuffer;
const az = new AnalyserNode(oc, {
fftSize: numberOfSamples * 2,
smoothingTimeConstant,
minDecibels,
maxDecibels,
});
source.connect(az).connect(oc.destination);
const msPerFrame = 1000 / fps;
let currentFrame = 0;
function process() {
const frequencies = new Uint8Array(az.frequencyBinCount);
az.getByteFrequencyData(frequencies);
// const times = new number[](az.frequencyBinCount);
// az.getByteTimeDomainData(times);
frameFrequencies[currentFrame] = frequencies;
const nextTime = (currentFrame + 1) * msPerFrame;
if (nextTime < lengthInMillis) {
currentFrame++;
const nextTimeSeconds = (currentFrame * msPerFrame) / 1000;
oc.suspend(nextTimeSeconds).then(process);
}
oc.resume();
}
oc.suspend(0).then(process);
source.start(0);
await oc.startRendering();
return frameFrequencies;
}
const buttonsDiv = document.createElement('div');
document.body.appendChild(buttonsDiv);
const initButton = document.createElement('button');
initButton.onclick = init;
initButton.innerHTML = 'Load audio'
buttonsDiv.appendChild(initButton);
const processButton = document.createElement('button');
processButton.disabled = true;
processButton.innerHTML = 'Process'
buttonsDiv.appendChild(processButton);
const resultElement = document.createElement('pre');
document.body.appendChild(resultElement)
async function init() {
initButton.disabled = true;
resultElement.innerText += 'Loading audio... ';
const audioContext = new AudioContext();
const arrayBuffer = await fetch('https://gist.githubusercontent.com/marcusstenbeck/da36a5fc2eeeba14ae9f984a580db1da/raw/84c53582d3936ac78625a31029022c8fdb734b2a/base64audio.txt').then(r => r.text()).then(fetch).then(r => r.arrayBuffer())
resultElement.innerText += 'finished.';
resultElement.innerText += '\nDecoding audio... ';
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
resultElement.innerText += 'finished.';
processButton.onclick = async () => {
processButton.disabled = true;
resultElement.innerText += '\nStart processing... ';
const t0 = Date.now();
await processFrequencyData(audioBuffer, {
fps: 30,
numberOfSamples: 2 ** 13,
maxDecibels: -25,
minDecibels: -70,
smoothingTimeConstant: 0.2,
});
resultElement.innerText += `finished in ${Date.now() - t0} ms`;
processButton.disabled = false;
};
processButton.disabled = false;
}
I guess this is really a bug in Safari. I'm able to reproduce it by rendering an OfflineAudioContext without any nodes. As soon as I use suspend()/resume() every invocation takes a little longer.
I'm only speculating here but I think it's possible that there is some internal mechanism which tries to prevent the rapid back and forth between the audio thread and the main thread. It almost feels like one of those login forms which takes a bit longer to validate the password every time you try.
Anyway I think you can avoid using suspend()/resume() for your particular use case. It should be possible to create an OfflineAudioContext for each of the slices instead. In order to get the same effect you would only render the particular slice with each OfflineAudioContext.
const currentTime = 0;
while (currentTime < duration) {
const offlineAudioContext = new OfflineAudioContext({
length: LENGTH_OF_ONE_SLICE,
sampleRate
});
const audioBufferSourceNode = new AudioBufferSourceNode(
offlineAudioContext,
{
buffer
}
);
const analyserNode = new AnalyserNode(offlineAudioContext);
audioBufferSourceNode.start(0, currentTime);
audioBufferSourceNode
.connect(analyserNode)
.connect(offlineAudioContext.destination);
await offlineAudioContext.startRendering();
const frequencies = new Uint8Array(analyserNode.frequencyBinCount);
analyserNode.getByteFrequencyData(frequencies);
// do something with the frequencies ...
currentTime += LENGTH_OF_ONE_SLICE * sampleRate;
}
I think the only thing missing would be the smoothing since each of those slices will have it's own AnalyserNode.

How to find difference between time in moment.js in React Native

How can I find difference time in React Native (I'm using moment):
Like:
let end = endTime; // 10:10:05
let start = startTime; // 10:10:03
moment.utc(moment(end," hh:mm:ss").diff(moment(start," hh:mm:ss"))).format("mm:ss")
//expected output: 00:00:02
You would need to use moment.duration
function timeRemaining (start, end) {
// get unix seconds
const began = moment(start).unix();
const stopped = moment(end).unix();
// find difference between unix seconds
const difference = stopped - began;
// apply to moment.duration
const duration = moment.duration(difference, 'seconds');
// then format the duration
const h = duration.hours().toString();
const m = duration.minutes().toString().padStart(2, '0');
const s = duration.seconds().toString().padStart(2, '0');
return `${h}:${m}:${s}`;
}

react native - updating progress in the UI

I'm trying to process some data in react native javascript while showing a progress percentage in the UI.
The naive implementation is something like:
readData(){
let i=0
let len = elements.length
for (; i < len; i++){
this.setState({progress:i/len});
this.process(elements[i]) // take some time
}
}
This, of course, will not work, as react native batch all setstate calls and call the last one.
Anyone has an idea how it should work?
Thanks!
If you want to update state after the progress you need to use callbacks or Promise.
Example
process(element, index, callback) {
setTimeOut(() => {
// some functions
if(callback && typeof callback === 'function') callback();
}, (10000* index))
}
readData(){
let i=0
let len = elements.length
for (; i < len; i++){
this.process(elements[i], i, () => {
const progress = i/len;
this.setState({progress});
});
}
}

Time out error using protractor with loops

Brief introduction to the problem. So my project is using BDD Framework (Cucumber) automated with help of Protractor/Selenium using Typescript as scripting language. I passed a table with multiple rows to the step definition and want to run the function in iteration mode using typescript/javascript. I pass the expected dropdowns values and verify it against the application. I came with the below solution with help of one topic on stack overflow. (Using protractor with loops)
But the problem is that it does not work all the time. Many times i have got function time out error.(Error: function timed out after 30000 milliseconds)
Can anyone please let me know what am i missing here? Any help would be greatly appreciated.
Please find below Cucumber and Typescript code.
Cucumber Step Definition_Screenshot
#then(/^.*verify the country data in both the citizenship drop downs$/, 'extratime', 30000)
public VerifyCountryData(table, callback: CallbackStepDefinition): void {
let promises = []
let dropcheck
let dropcheck1
let promise
let noOfRows
var i,j;
var i1,j1;
var k,l;
var funcs = [];
for (i = 0; i < 2; i++) {
let index = i;
funcs[i] = function(index) {
promises.push(element(by.model('vm.citizenships['+index+'].citizenshipCd')).all(by.tagName('option')).getText().then((CitizenValueList) => {
var dropdown = table.rows()[index][1].split(";")
for (i1 = 0; i1 < dropdown.length; i1++) {
dropcheck = false;
for (j1 = 0; j1 < CitizenValueList.length; j1++) {
if (dropdown[i1] === CitizenValueList[j1]) {
dropcheck = true;
break;
}
}
if (!dropcheck) {
callback("Passed value: '" + dropdown[i1] + "' not found")
}
}
for (k = 0; k < CitizenValueList.length; k++) {
dropcheck1 = false;
for (l = 0; l < dropdown.length; l++) {
if (CitizenValueList[k] === dropdown[l]) {
dropcheck1 = true;
break;
}
}
if (!dropcheck1) {
callback("Application value: '" + CitizenValueList[k] + "' not found in expected")
}
}
}))
}.bind(null, i);
}
for (j = 0; j < 2; j++) {
funcs[j]();
}
Promise.all(promises).then(() => {
callback();
}, (error) => {
callback(error);
});
}
}
as far as I can see in your code you loops will take more then 30 seconds, that's the timeout you gave in the #then(/^.*verify the country data in both the citizenship drop downs$/, 'extratime', 30000). If you change it to for example 60000 you have more time for this method.
Upgrading the time is a temporary solution in my opinion, you also need to find the root-cause of exceeding the 30 seconds time limit. One of the problems can be a slow connection which results in not retrieving the webdriver-calls fast enough. Are you testing it locally or against a cloud solution? The experience I have with cloud solutions is that 1 webdriver-call can take up to 1 second. If you compare it to local testing than local webdriver-calls just take a few milliseconds.
About the code. Depending on the version of Typescript you have (I think you need at least version 2.1) you can use async/await. This will remove all the promises.push(..), Promise.all(promises) hell and introduce a more clean code like this
#then(/^.*verify the country data in both the citizenship drop downs$/, 'extratime', 30000)
public async VerifyCountryData(table): Promise < void > {
const citizenValueListOne = await element(by.model('vm.citizenships[1].citizenshipCd')).all(by.tagName('option')).getText();
const dropdownOne = table.rows()[1][1].split(';');
const citizenValueListTwo = await element(by.model('vm.citizenships[2].citizenshipCd')).all(by.tagName('option')).getText();
const dropdownTwo = table.rows()[2][2].split(';');
for (let i1 = 0; i1 < dropdownOne.length; i1++) {
let dropdownOnecheck = false;
for (let j1 = 0; j1 < citizenValueListOne.length; j1++) {
if (dropdownOne[i1] === citizenValueListOne[j1]) {
dropdownOnecheck = true;
break;
}
}
if (!dropdownOnecheck) {
Promise.reject(`Passed value: '${dropdownOne[i1]}' not found`);
}
}
for (let k = 0; k < citizenValueListTwo.length; k++) {
let dropdownTwocheck = false;
for (let l = 0; l < dropdownTwo.length; l++) {
if (citizenValueListTwo[k] === dropdownTwo[l]) {
dropdownTwocheck = true;
break;
}
}
if (!dropdownTwocheck) {
Promise.reject(`Application value: '${citizenValueListTwo[k]}' not found in expected`);
}
}
return Promise.resolve();
}
This can also have an impact on the execution time.
Hope this helps

results.row[i] is undefined using react-native-db-models

Im new to React Native and Im using react-native-db-models. I have searched stackoverflow for fetching the data and it gave me this code below
DB.users.get_all((result) => {
let data = [];
for (let i = 1; i <= result.totalrows; i++) {
data.push(result.rows[i]);
}
but result.rows[i] returns undefined. Any ideas how and why?
I tried my own solution but this time it gave me another problem. This is my code
DB.expense.get_all(function(result){
var data = [];
for (let i = 1; i <= result.totalrows; i++) {
let j = result.autoinc;
let id = j - i;
DB.expense.get_id(id, function(results){
data.push(result)
})
}
}
when I put console.log(data) after data.push(result) it works fine. But when I put console.log(data) outside DB.expense.get_id function, console.log(data) returns an empty array.
I really need your help guys