You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native数组对象数据计算代码重构:求低耗时优化方案

问题描述

我正在开发一款React Native Android/iOS应用,现有如下结构的对象数组:

const shots= [
{"heatNumber": 1, "heatShotHit": 0, "heatShotNumber": 1, "hit": false, "id": "e404bd61-0a96-4e21-b6aa-36ff433f16ad", "rangeNumber": 1, "shotNumber": 1, "shotValue": 0, "stationNumber": 1, "timeFromStart": 0, "xEnd": 6, "xStart": 5, "yEnd": 5, "yStart": 6}, 

{"heatNumber": 1, "heatShotHit": 1, "heatShotNumber": 2, "hit": true, "id": "1badd0dc-59a5-4b2f-97b4-db5fdc72e13d", "rangeNumber": 1, "shotNumber": 2, "shotValue": 10, "stationNumber": 1, "timeFromStart": 163, "xEnd": 2, "xStart": 1, "yEnd": 1, "yStart": 2}, 

{"heatNumber": 1, "heatShotHit": 2, "heatShotNumber": 3, "hit": true, "id": "50a7a92c-3b26-49df-8ab8-677d6978a0a2", "rangeNumber": 1, "shotNumber": 3, "shotValue": 10, "stationNumber": 1, "timeFromStart": 268, "xEnd": 1, "xStart": 1, "yEnd": 1, "yStart": 1}, 

{"heatNumber": 1, "heatShotHit": 3, "heatShotNumber": 4, "hit": true, "id": "04b82166-1466-4b92-8c45-5ef2ecce9930", "rangeNumber": 1, "shotNumber": 4, "shotValue": 10, "stationNumber": 1, "timeFromStart": 381, "xEnd": 1, "xStart": 1, "yEnd": 1, "yStart": 1}];

需要从中获取三个数值:

  • 总射击数(数组内对象总数)
  • 最终命中数(finalHeatShotHit = 最后一个对象的heatShotHit值 - 第一个对象的heatShotHit值)
  • 未命中数(总射击数 - 最终命中数)

我编写了如下代码:

const heatCount = Object.keys(shots).length;
const valueOfHitCalc = shots.map(a=>a.heatShotHit);
const hit = valueOfHitCalc[valueOfHitCalc.length-1] - valueOfHitCalc[0];
const miss = heatCount - hit;

能否提供更优的代码重构方案,以降低执行时间?


优化方案

你的代码有两处可以显著降低执行开销的优化点:

  1. 总射击数直接使用数组原生的length属性即可,Object.keys(shots).length会额外遍历数组生成键数组,完全没必要。
  2. 计算命中数时,不需要用map遍历整个数组生成新数组——你只需要第一个和最后一个元素的heatShotHit值,直接通过索引访问对应元素,省去了遍历所有元素的时间,数组规模越大,优化效果越明显。

优化后的代码:

const heatCount = shots.length;
// 可选链+默认值处理数组为空的边界情况
const firstHitValue = shots[0]?.heatShotHit || 0;
const lastHitValue = shots[heatCount - 1]?.heatShotHit || 0;
const hit = lastHitValue - firstHitValue;
const miss = heatCount - hit;

如果能确保shots数组永远不为空,可以去掉边界处理的逻辑,简化为:

const heatCount = shots.length;
const hit = shots[heatCount - 1].heatShotHit - shots[0].heatShotHit;
const miss = heatCount - hit;

内容的提问来源于stack exchange,提问作者Zahid Abdullah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:25:47