javascript - 从 RN 中的 setTimeout 或 Alert 回调中调度 redux 操作时性能下降
问题描述
对此可能有一个很好的解释,但目前我很困惑。
所以用例是我想在一个setTimeout
块中或Alert.alert
在 RN 的回调中调度一个 redux 操作。我注意到的是,如果代码以这种方式运行,那么它会慢得多。
例如,代码如下:
import React from 'react';
import { connect } from 'react-redux';
import { addTag } from '../redux/actions';
import { Button, View, Alert } from 'react-native';
export const HomePerfTest = connect(
null,
dispatch => ({
addTag: (tag, category) => dispatch(addTag(tag, category)),
})
)(props => (
<View>
<Button
title="Press me"
onPress={() => {
addRandomTags(props.addTag);
}}
/>
<Button
title="Press me"
onPress={() => {
Alert.alert('Add random tags', null, [
{
text: 'Yes',
onPress: () => {
addRandomTags(props.addTag);
},
},
{
text: 'No',
},
]);
}}
/>
</View>
));
const addRandomTags = addTag => {
for (let i = 0; i < 10; i++) {
measure(
() =>
addTag(
{
name: 'test' + i,
},
'test'
),
'addTag'
);
}
};
const measure = (f, label) => {
var t0 = new Date().getTime();
const value = f();
var t1 = new Date().getTime();
console.log(label + ' took ' + (t1 - t0) + ' milliseconds.');
return value;
};
现在,当按下第一个按钮时,addTag
运行时间为 0-1 毫秒。当按下第二个按钮(然后单击是)时,需要 4-8 毫秒,因此会慢几倍。
这种情况并没有那么糟糕,但我已经在我的应用程序的另一个页面中实现了类似的东西,其中差异很大。正常运行大约需要 2 毫秒,如果从Alert
回调中运行,则需要 >100 毫秒才能执行。
现在,我通过使用与 RN Alert 不同的警报模块来解决问题。但是我注意到如果我只是将代码包装在setTimeout
setTimeout(() => addRandomTags(props.addTag));
任何解释将不胜感激。
更新- 我在包装代码时也可以看到完全相同的延迟requestAnimationFrame
。
解决方案
推荐阅读
- javascript - HTML 视频元素到 base64
- c++ - 如何为std函数分配空间并做memcpy?
- c# - 与 Promise.all 等效的 C# 是什么?
- bash - Mutt bash脚本可以从命令行发送电子邮件,但不能从motioneye通知钩子发送电子邮件
- javascript - 如何将对象数组转换为逗号分隔的字符串?
- google-apps-script - 关于单元格选择
- c++ - 如何使用终端命令从 C++ 程序中打开多个图像?
- javascript - 将范围滑块绑定到图像序列
- angular - 在反应式表单模块的 auditTime 方法的订阅块中测试值
- php - 连接两个 MySQL 表并在表中显示结果