ui: Replace non-null assertions on index accesses with checked constructs Since noUncheckedIndexedAccess was enabled, many index accesses were silenced with '!'. This removes those assertions in the obvious cases, following the guidance in AGENTS-ui.md: - Convert index loops to for...of / arr.entries() where the index is only used for indexing (charts, datagrid, DataExplorer, plugins). - Read-then-check instead of checking length and then indexing (scroll details panel, line chart, trace config version check). - Use ensureDefined() where an invariant genuinely needs asserting. - Widen sqlValuesEqual() to accept undefined, which it already normalised, dropping the assertions in groupPathsEqual(). - Zip key/column pairs once per decode in SliceTrack so the per-row loop needs no indexing at all. Hot paths keep indexed iteration (with a comment explaining why the index is provably in range): the flamegraph renderer and the per-frame slice hover-variant loop, where .entries() would allocate a pair per iteration. No behaviour changes are intended. ui/build --typecheck, ESLint and Prettier are clean; all unit tests pass.
diff --git a/ui/src/base/fuzzy_unittest.ts b/ui/src/base/fuzzy_unittest.ts index 9324d88..6461903 100644 --- a/ui/src/base/fuzzy_unittest.ts +++ b/ui/src/base/fuzzy_unittest.ts
@@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +import {ensureDefined} from './assert'; import {fuzzySearch} from './fuzzy'; describe('fuzzySearch', () => { @@ -185,14 +186,16 @@ it('handles empty search query for multi-key lookup', () => { const results = fuzzySearch(items, keyLookups, ''); expect(results.length).toBe(items.length); - for (let i = 0; i < items.length; i++) { - expect(results[i]!.item).toEqual(items[i]); - expect(results[i]!.score).toBe(1); - expect(results[i]!.segments[0]).toEqual([ - {matching: false, value: items[i]!.name}, + for (const [i, item] of items.entries()) { + // `results` is aligned with `items` (checked above). + const result = ensureDefined(results[i]); + expect(result.item).toEqual(item); + expect(result.score).toBe(1); + expect(result.segments[0]).toEqual([ + {matching: false, value: item.name}, ]); - expect(results[i]!.segments[1]).toEqual([ - {matching: false, value: items[i]!.source}, + expect(result.segments[1]).toEqual([ + {matching: false, value: item.source}, ]); } });
diff --git a/ui/src/chrome_extension/trace_config_utils.ts b/ui/src/chrome_extension/trace_config_utils.ts index 353db67..1c7e043 100644 --- a/ui/src/chrome_extension/trace_config_utils.ts +++ b/ui/src/chrome_extension/trace_config_utils.ts
@@ -44,8 +44,10 @@ const runVerArray = runningVersion.split('.').map(Number); for (let index = 0; index < minVerArray.length; index++) { - if (runVerArray[index] === minVerArray[index]) continue; - return runVerArray[index]! > minVerArray[index]!; + const runPart = runVerArray[index] ?? 0; + const minPart = minVerArray[index] ?? 0; + if (runPart === minPart) continue; + return runPart > minPart; } return true; // Exact version match. }
diff --git a/ui/src/components/tracks/slice_track.ts b/ui/src/components/tracks/slice_track.ts index a438f9a..0ba8659 100644 --- a/ui/src/components/tracks/slice_track.ts +++ b/ui/src/components/tracks/slice_track.ts
@@ -928,8 +928,9 @@ const tsCol = cols.__ts; const countCol = cols.__count; const depthCol = cols.__depth; - const schemaKeys = Object.keys(dataset.schema); - const schemaCols = schemaKeys.map((k) => cols[k]!); + const schema = Object.keys(dataset.schema).map( + (k) => [k, cols[k]] as const, + ); const xs = new Float32Array(tsCol); const depths = new Uint16Array(depthCol); @@ -944,7 +945,7 @@ // would change the track API. // TODO(stevegolton): Change the getTitle(), getSubtitle(), getColor() // callbacks to avoid having to build a row object for every row. - const row = this.buildSchemaRow(schemaKeys, schemaCols, i); + const row = this.buildSchemaRow(schema, i); const title = this.getTitle(row); const subtitle = this.getSubtitle(row); const colorScheme = this.getColor(row, title); @@ -1037,8 +1038,9 @@ const countCol = cols.__count; const depthCol = cols.__depth; const incompleteCol = cols.__incomplete; - const schemaKeys = Object.keys(dataset.schema); - const schemaCols = schemaKeys.map((k) => cols[k]!); + const schema = Object.keys(dataset.schema).map( + (k) => [k, cols[k]] as const, + ); const starts = new Float32Array(startCol); const ends = new Float32Array(count); @@ -1052,7 +1054,7 @@ if (task.shouldYield()) await task.yield(); } - const row = this.buildSchemaRow(schemaKeys, schemaCols, i); + const row = this.buildSchemaRow(schema, i); const title = this.getTitle(row); const subtitle = this.getSubtitle(row); const colorScheme = this.getColor(row, title); @@ -1085,16 +1087,18 @@ }; } - // Reads the dataset.schema columns out of the decoded columnar arrays (cols[k] - // holds the data for schema key k) into a per-row object for the callbacks. + // Reads the dataset.schema columns out of the decoded columnar arrays into a + // per-row object for the callbacks. `schema` pairs each schema key with its + // column; it is zipped once per decode so this per-row hot loop allocates + // nothing. private buildSchemaRow( - keys: readonly string[], - cols: readonly ArrayLike<SqlValue>[], + schema: readonly (readonly [string, ArrayLike<SqlValue> | undefined])[], i: number, ): InferRowType<T> { const row: Record<string, SqlValue> = {}; - for (let k = 0; k < keys.length; k++) { - row[keys[k]!] = cols[k]![i]!; + for (const [key, col] of schema) { + // A missing value is normalised to null, as SQL has no undefined. + row[key] = col?.[i] ?? null; } return row as InferRowType<T>; } @@ -1145,7 +1149,8 @@ if (hoveredSlice || highlightedSliceName !== undefined) { const hoveredSliceId = hoveredSlice?.id; const hoveredTitle = highlightedSliceName; - // Index based iteration is more efficient than .map + // Hot path (every frame): indexed iteration avoids the per-iteration + // pair allocation of `.entries()`. `i` is provably in range. for (let i = 0; i < slices.length; i++) { const {id, title} = slices[i]!; variants[i] =
diff --git a/ui/src/components/widgets/charts_svg/line_chart_svg.ts b/ui/src/components/widgets/charts_svg/line_chart_svg.ts index 48b1d51..debfb6f 100644 --- a/ui/src/components/widgets/charts_svg/line_chart_svg.ts +++ b/ui/src/components/widgets/charts_svg/line_chart_svg.ts
@@ -14,6 +14,7 @@ import m from 'mithril'; import {classNames} from '../../../base/classnames'; +import {ensureDefined} from '../../../base/assert'; import {max, min} from '../../../base/array_utils'; import {clamp} from '../../../base/math_utils'; import {exists} from '../../../base/utils'; @@ -606,7 +607,8 @@ this.hover = undefined; return; } - if (seriesPlots.length === 0 || seriesPlots[0]!.points.length === 0) return; + const firstPlot = seriesPlots[0]; + if (firstPlot === undefined || firstPlot.points.length === 0) return; const px = e.clientX - rect.left; if (px < padLeft || px > padLeft + plotW) { if (this.hover !== undefined) { @@ -617,11 +619,11 @@ const xVal = xRange.min + ((px - padLeft) / (plotW || 1)) * (xRange.max - xRange.min); // Nearest index in series 0 (assumes shared x; first series is reference). - const pts = seriesPlots[0]!.points; + const pts = firstPlot.points; let bestIdx = 0; let bestDist = Infinity; - for (let i = 0; i < pts.length; i++) { - const d = Math.abs(pts[i]!.x - xVal); + for (const [i, p] of pts.entries()) { + const d = Math.abs(p.x - xVal); if (d < bestDist) { bestDist = d; bestIdx = i; @@ -631,7 +633,8 @@ clientX: e.clientX, clientY: e.clientY, index: bestIdx, - xValue: pts[bestIdx]!.x, + // `pts` is non-empty (checked above). + xValue: ensureDefined(pts[bestIdx]).x, }; } } @@ -650,8 +653,7 @@ // Stacked: assume aligned x values across series; sum cumulatively. const result: SeriesPlot[] = []; const cum = new Map<number, number>(); - for (let i = 0; i < series.length; i++) { - const s = series[i]!; + for (const [i, s] of series.entries()) { const stackedPoints: {x: number; y: number; raw: number}[] = []; for (const p of s.points) { const prev = cum.get(p.x) ?? 0; @@ -675,8 +677,7 @@ ): string { if (s.points.length === 0) return ''; let d = ''; - for (let i = 0; i < s.points.length; i++) { - const p = s.points[i]!; + for (const [i, p] of s.points.entries()) { d += (i === 0 ? 'M' : 'L') + xToPx(p.x) + ',' + yToPx(p.y) + ' '; } return d.trim(); @@ -696,17 +697,22 @@ const top = s.points; const bottom = index > 0 ? all[index - 1]!.points : undefined; let d = ''; - for (let i = 0; i < top.length; i++) { - d += - (i === 0 ? 'M' : 'L') + xToPx(top[i]!.x) + ',' + yToPx(top[i]!.y) + ' '; + for (const [i, p] of top.entries()) { + d += (i === 0 ? 'M' : 'L') + xToPx(p.x) + ',' + yToPx(p.y) + ' '; } if (bottom !== undefined) { + // Reverse iteration: `i` is provably in range. for (let i = bottom.length - 1; i >= 0; i--) { d += 'L' + xToPx(bottom[i]!.x) + ',' + yToPx(bottom[i]!.y) + ' '; } } else { - d += 'L' + xToPx(top[top.length - 1]!.x) + ',' + baselinePx + ' '; - d += 'L' + xToPx(top[0]!.x) + ',' + baselinePx + ' '; + // `top` is non-empty (checked above). + const first = top[0]; + const last = top[top.length - 1]; + if (first !== undefined && last !== undefined) { + d += 'L' + xToPx(last.x) + ',' + baselinePx + ' '; + d += 'L' + xToPx(first.x) + ',' + baselinePx + ' '; + } } d += 'Z'; return d;
diff --git a/ui/src/components/widgets/datagrid/datagrid.ts b/ui/src/components/widgets/datagrid/datagrid.ts index f5435ee..b8f63a4 100644 --- a/ui/src/components/widgets/datagrid/datagrid.ts +++ b/ui/src/components/widgets/datagrid/datagrid.ts
@@ -97,7 +97,10 @@ const QUICK_FILTER_MATCH_CLASS = 'pf-data-grid__cell--quick-filter-match'; // Compare two SqlValues for equality, handling nulls, undefined, and different types. -function sqlValuesEqual(a: SqlValue, b: SqlValue): boolean { +function sqlValuesEqual( + a: SqlValue | undefined, + b: SqlValue | undefined, +): boolean { // Normalize undefined to null (SQL has no concept of undefined) const normA = a === undefined ? null : a; const normB = b === undefined ? null : b; @@ -119,7 +122,7 @@ function groupPathsEqual(a: GroupPath, b: GroupPath): boolean { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { - if (!sqlValuesEqual(a[i]!, b[i]!)) return false; + if (!sqlValuesEqual(a[i], b[i])) return false; } return true; } @@ -2043,8 +2046,7 @@ // Build aggregate columns const aggregates = pivot.aggregates ?? []; - for (let i = 0; i < aggregates.length; i++) { - const agg = aggregates[i]!; + for (const [i, agg] of aggregates.entries()) { const sort = agg.sort; const alias = getAggregateAlias(agg); @@ -2433,11 +2435,14 @@ columnNames = buildColumnNames(schema, fieldPaths); // Map aliases to field paths for column name lookup - for (let i = 0; i < columns.length; i++) { - const alias = columns[i]!; - const field = fieldPaths[i]!; + for (const col of this.columns) { + const alias = getColumnAlias(col); + const field = col.field; if (alias !== field) { - columnNames[alias] = columnNames[field]!; + const name = columnNames[field]; + if (name !== undefined) { + columnNames[alias] = name; + } } } }
diff --git a/ui/src/components/widgets/datagrid/sql_data_source/rollup_tree.ts b/ui/src/components/widgets/datagrid/sql_data_source/rollup_tree.ts index 327fabd..37c411e 100644 --- a/ui/src/components/widgets/datagrid/sql_data_source/rollup_tree.ts +++ b/ui/src/components/widgets/datagrid/sql_data_source/rollup_tree.ts
@@ -81,9 +81,8 @@ } const conditions: string[] = []; - for (let i = 0; i < path.length; i++) { + for (const [i, value] of path.entries()) { const col = `${columnPrefix}__group_${i}`; - const value = path[i]; if (value === null || value === undefined) { conditions.push(`${col} IS NULL`); } else {
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/queries.ts b/ui/src/plugins/com.android.HeapDumpExplorer/queries.ts index b546cab..6eebe34 100644 --- a/ui/src/plugins/com.android.HeapDumpExplorer/queries.ts +++ b/ui/src/plugins/com.android.HeapDumpExplorer/queries.ts
@@ -844,13 +844,12 @@ for (const [targetId, chain] of pathChains) { const path: PathEntry[] = []; - for (let i = 0; i < chain.length; i++) { - const row = nodeMap.get(chain[i]!); + for (const [i, node] of chain.entries()) { + const row = nodeMap.get(node); if (!row) continue; + const next = chain[i + 1]; const field = - i < chain.length - 1 - ? (fieldMap.get(`${chain[i]}:${chain[i + 1]}`) ?? '') - : ''; + next !== undefined ? (fieldMap.get(`${node}:${next}`) ?? '') : ''; path.push({row, field, isDominator: false}); } if (path.length > 0) result.set(targetId, path); @@ -985,13 +984,12 @@ for (const [targetId, chain] of pathChains) { const path: PathEntry[] = []; - for (let i = 0; i < chain.length; i++) { - const row = nodeMap.get(chain[i]!); + for (const [i, node] of chain.entries()) { + const row = nodeMap.get(node); if (!row) continue; + const next = chain[i + 1]; const field = - i < chain.length - 1 - ? (fieldMap.get(`${chain[i]}:${chain[i + 1]}`) ?? '') - : ''; + next !== undefined ? (fieldMap.get(`${node}:${next}`) ?? '') : ''; path.push({row, field, isDominator: true}); } if (path.length > 0) result.set(targetId, path); @@ -1153,12 +1151,12 @@ const jit = jsonRes.iter({data: STR_NULL}); if (jit.valid() && jit.data !== null) { const values = JSON.parse(jit.data) as Array<number | string | boolean>; - for (let i = 0; i < values.length; i++) { + for (const [i, v] of values.entries()) { arrayElems.push({ idx: i, value: { kind: 'prim', - v: formatPrimValue(arrayElementType, values[i]!), + v: formatPrimValue(arrayElementType, v), }, }); }
diff --git a/ui/src/plugins/dev.perfetto.AutoPinAndExpandTracks/index.ts b/ui/src/plugins/dev.perfetto.AutoPinAndExpandTracks/index.ts index 63af99e..3fc300d 100644 --- a/ui/src/plugins/dev.perfetto.AutoPinAndExpandTracks/index.ts +++ b/ui/src/plugins/dev.perfetto.AutoPinAndExpandTracks/index.ts
@@ -258,8 +258,7 @@ let mostSimilarTrack: LocalTrack | undefined = undefined; let mostSimilarTrackDifferenceScore: number = 0; - for (let i = 0; i < localTracks.length; i++) { - const localTrack = localTracks[i]!; + for (const localTrack of localTracks) { const differenceScore = this.calculateSimilarityScore( localTrack.savedTrack, savedTrack,
diff --git a/ui/src/plugins/dev.perfetto.DataExplorer/pbtxt_import.ts b/ui/src/plugins/dev.perfetto.DataExplorer/pbtxt_import.ts index a629f43..b2d8fa0 100644 --- a/ui/src/plugins/dev.perfetto.DataExplorer/pbtxt_import.ts +++ b/ui/src/plugins/dev.perfetto.DataExplorer/pbtxt_import.ts
@@ -126,14 +126,14 @@ }; // Process metric_template_specs. - for (let i = 0; i < allTemplateSpecs.length; i++) { + for (const [i, templateSpec] of allTemplateSpecs.entries()) { const chainX = START_X + i * METRIC_CHAIN_GAP_X; mergeResult( acc, buildNodesFromMetricConfig( { - query: allTemplateSpecs[i]!.query, - metricsState: templateSpecToMetricsState(allTemplateSpecs[i]!), + query: templateSpec.query, + metricsState: templateSpecToMetricsState(templateSpec), }, chainX, sharedQueries, @@ -144,14 +144,14 @@ // Process metric_specs (simpler, single-value metrics). const metricSpecOffset = allTemplateSpecs.length; - for (let i = 0; i < allMetricSpecs.length; i++) { + for (const [i, metricSpec] of allMetricSpecs.entries()) { const chainX = START_X + (metricSpecOffset + i) * METRIC_CHAIN_GAP_X; mergeResult( acc, buildNodesFromMetricConfig( { - query: allMetricSpecs[i]!.query, - metricsState: metricSpecToMetricsState(allMetricSpecs[i]!), + query: metricSpec.query, + metricsState: metricSpecToMetricsState(metricSpec), }, chainX, sharedQueries,
diff --git a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/graph/graph.ts b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/graph/graph.ts index 7f40fca..8ea701b 100644 --- a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/graph/graph.ts +++ b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/graph/graph.ts
@@ -251,12 +251,12 @@ } const menuItems: m.Children[] = []; - for (let i = 0; i < sections.length; i++) { - if (i > 0) { + for (const section of sections) { + if (menuItems.length > 0) { menuItems.push(m(MenuDivider)); } - menuItems.push(m(MenuTitle, {label: sections[i]!.title})); - menuItems.push(...sections[i]!.items); + menuItems.push(m(MenuTitle, {label: section.title})); + menuItems.push(...section.items); } return menuItems; } @@ -740,12 +740,12 @@ ].filter((s) => s.items.length > 0); const addNodeMenuItems: m.Children[] = []; - for (let i = 0; i < sections.length; i++) { - if (i > 0) { + for (const section of sections) { + if (addNodeMenuItems.length > 0) { addNodeMenuItems.push(m(MenuDivider)); } - addNodeMenuItems.push(m(MenuTitle, {label: sections[i]!.title})); - addNodeMenuItems.push(...sections[i]!.items); + addNodeMenuItems.push(m(MenuTitle, {label: section.title})); + addNodeMenuItems.push(...section.items); } addNodeMenuItems.push(m(MenuDivider)); addNodeMenuItems.push(
diff --git a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/graph/node_box.ts b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/graph/node_box.ts index 5f5f03c..6e99bb0 100644 --- a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/graph/node_box.ts +++ b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/graph/node_box.ts
@@ -72,12 +72,12 @@ } const menuItems: m.Children[] = []; - for (let i = 0; i < sections.length; i++) { - if (i > 0) { + for (const section of sections) { + if (menuItems.length > 0) { menuItems.push(m(MenuDivider)); } - menuItems.push(m(MenuTitle, {label: sections[i]!.title})); - menuItems.push(...sections[i]!.items); + menuItems.push(m(MenuTitle, {label: section.title})); + menuItems.push(...section.items); } return m(
diff --git a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/connections_unittest.ts b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/connections_unittest.ts index 07a3c18..29eacba 100644 --- a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/connections_unittest.ts +++ b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/connections_unittest.ts
@@ -2595,8 +2595,8 @@ ); // Union allows unbounded inputs - for (let i = 0; i < nodes.length; i++) { - addConnection(nodes[i]!, unionNode, i); + for (const [i, node] of nodes.entries()) { + addConnection(node, unionNode, i); } // With 10 inputs, validation should pass (unbounded max)
diff --git a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/group_node/inner_graph_preview.ts b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/group_node/inner_graph_preview.ts index 5a4e244..c3c590d 100644 --- a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/group_node/inner_graph_preview.ts +++ b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/group_node/inner_graph_preview.ts
@@ -135,10 +135,10 @@ const nodeSpacingX = 250; const nodes: GraphNode[] = []; - for (let i = 0; i < roots.length; i++) { + for (const [i, root] of roots.entries()) { nodes.push({ ...buildReadOnlyNodeConfig( - roots[i]!, + root, innerSet, connectedInputs, connectedOutputs, @@ -150,8 +150,7 @@ // Add "Input N" nodes for external connections. // Grey out disconnected inputs. - for (let i = 0; i < groupNode.externalConnections.length; i++) { - const conn = groupNode.externalConnections[i]!; + for (const [i, conn] of groupNode.externalConnections.entries()) { const isConnected = groupNode.secondaryInputs.connections.has( conn.groupPort, );
diff --git a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/interval_intersect_node.ts b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/interval_intersect_node.ts index ed7ad25..297740d 100644 --- a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/interval_intersect_node.ts +++ b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/interval_intersect_node.ts
@@ -196,8 +196,7 @@ } // For each input node, add id_N, ts_N, dur_N - for (let i = 0; i < inputNodes.length; i++) { - const node = inputNodes[i]; + for (const [i, node] of inputNodes.entries()) { if (node === undefined) continue; // Find the actual column info for id to get its type
diff --git a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/metrics_export_modal.ts b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/metrics_export_modal.ts index 6e17ae5..15c1efb 100644 --- a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/metrics_export_modal.ts +++ b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/metrics_export_modal.ts
@@ -252,7 +252,7 @@ resultStates.set(vc.column, {kind: 'error', message: result.error}); } } else if (result.protoSummary) { - for (let i = 0; i < valueColumns.length; i++) { + for (const [i, valueColumn] of valueColumns.entries()) { const parsed = parseMetricBundleForValue( result.protoSummary, metricIdPrefix, @@ -261,12 +261,12 @@ i, ); if (parsed !== undefined && parsed.rows.length > 0) { - resultStates.set(valueColumns[i]!.column, { + resultStates.set(valueColumn.column, { kind: 'data', result: parsed, }); } else { - resultStates.set(valueColumns[i]!.column, { + resultStates.set(valueColumn.column, { kind: 'error', message: 'No metric data found', });
diff --git a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/trace_summary_results_panel.ts b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/trace_summary_results_panel.ts index ab2cf39..8055dff 100644 --- a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/trace_summary_results_panel.ts +++ b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/nodes/trace_summary_results_panel.ts
@@ -99,8 +99,7 @@ valueIndex: 0, }); } else { - for (let i = 0; i < specs.length; i++) { - const spec = specs[i]!; + for (const [i, spec] of specs.entries()) { metrics.push({ metricId: spec.id ?? `${bundle.bundleId ?? 'unknown'}_${i}`, valueName: spec.value ?? 'value', @@ -126,9 +125,9 @@ const rows: Row[] = []; for (const row of bundle.row ?? []) { const rowData: Row = {}; - for (let i = 0; i < dimensionNames.length; i++) { + for (const [i, dimName] of dimensionNames.entries()) { const dimValue = row.dimension?.[i]; - rowData[dimensionNames[i]!] = + rowData[dimName] = dimValue !== undefined && dimValue !== null ? parseDimensionValue(dimValue) : null;
diff --git a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/structured_query_builder.ts b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/structured_query_builder.ts index 1d56be5..3649b43 100644 --- a/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/structured_query_builder.ts +++ b/ui/src/plugins/dev.perfetto.DataExplorer/query_builder/structured_query_builder.ts
@@ -334,8 +334,8 @@ // Create reference queries for intervals with dur filter const intervals: protos.PerfettoSqlStructuredQuery[] = []; - for (let i = 0; i < intervalQueries.length; i++) { - const intervalId = extractQueryId(intervalQueries[i]); + for (const [i, intervalQuery] of intervalQueries.entries()) { + const intervalId = extractQueryId(intervalQuery); if (!intervalId) return undefined; intervals.push( this.createDurFilteredRef(intervalId, `${actualNodeId}_interval_${i}`), @@ -679,8 +679,8 @@ const actualNodeId = nodeId ?? nextNodeId(); const refQueries: protos.PerfettoSqlStructuredQuery[] = []; - for (let i = 0; i < queries.length; i++) { - const queryId = extractQueryId(queries[i]); + for (const [i, query] of queries.entries()) { + const queryId = extractQueryId(query); if (!queryId) return undefined; refQueries.push(this.createRef(queryId, `${actualNodeId}_union_${i}`)); }
diff --git a/ui/src/plugins/dev.perfetto.Gpu/index.ts b/ui/src/plugins/dev.perfetto.Gpu/index.ts index 9cae7d2..3716b55 100644 --- a/ui/src/plugins/dev.perfetto.Gpu/index.ts +++ b/ui/src/plugins/dev.perfetto.Gpu/index.ts
@@ -486,8 +486,8 @@ .sort((a, b) => a[1].localeCompare(b[1])) .map(([id]) => id); const groupSortOrder = new Map<number, number>(); - for (let i = 0; i < sortedGroupIds.length; i++) { - groupSortOrder.set(sortedGroupIds[i]!, CUSTOM_GROUP_SORT_BASE + i); + for (const [i, id] of sortedGroupIds.entries()) { + groupSortOrder.set(id, CUSTOM_GROUP_SORT_BASE + i); } // Count ungrouped tracks per type to decide if a sub-group is needed,
diff --git a/ui/src/plugins/dev.perfetto.Memscope/views/tabs/processes.ts b/ui/src/plugins/dev.perfetto.Memscope/views/tabs/processes.ts index 4aa98fc..9c2f81d 100644 --- a/ui/src/plugins/dev.perfetto.Memscope/views/tabs/processes.ts +++ b/ui/src/plugins/dev.perfetto.Memscope/views/tabs/processes.ts
@@ -213,19 +213,18 @@ const timestamps = [...tsSet].sort((a, b) => a - b); if (timestamps.length < 2) return undefined; const pointsByBucket = new Map<number, {x: number; y: number}[]>(); - for (let i = 0; i < OOM_SCORE_BUCKETS.length; i++) pointsByBucket.set(i, []); + for (const [i] of OOM_SCORE_BUCKETS.entries()) pointsByBucket.set(i, []); for (const ts of timestamps) { const x = (ts - t0) / 1e9; const bucketMap = byBucketTs.get(ts)!; - for (let i = 0; i < OOM_SCORE_BUCKETS.length; i++) { - pointsByBucket.get(i)!.push({x, y: bucketMap.get(i) ?? 0}); + for (const [i, points] of pointsByBucket) { + points.push({x, y: bucketMap.get(i) ?? 0}); } } const series: LineChartSeries[] = []; - for (let i = 0; i < OOM_SCORE_BUCKETS.length; i++) { - const points = pointsByBucket.get(i)!; - if (points.some((p) => p.y > 0)) { - const bucket = OOM_SCORE_BUCKETS[i]!; + for (const [i, bucket] of OOM_SCORE_BUCKETS.entries()) { + const points = pointsByBucket.get(i); + if (points !== undefined && points.some((p) => p.y > 0)) { series.push({name: bucket.name, points, color: chipColor(bucket.color)}); } }
diff --git a/ui/src/plugins/dev.perfetto.MetricsPage/metrics_page.ts b/ui/src/plugins/dev.perfetto.MetricsPage/metrics_page.ts index c5982e5..1488774 100644 --- a/ui/src/plugins/dev.perfetto.MetricsPage/metrics_page.ts +++ b/ui/src/plugins/dev.perfetto.MetricsPage/metrics_page.ts
@@ -269,15 +269,13 @@ const rowData: Row = {}; // Add dimensions - for (let i = 0; i < dimensionNames.length; i++) { - const dimName = dimensionNames[i]!; + for (const [i, dimName] of dimensionNames.entries()) { const dimValue = row.dimension?.[i]; rowData[dimName] = dimValue ? getDimensionValue(dimValue) : null; } // Add all values (templates can have multiple value columns) - for (let i = 0; i < valueNames.length; i++) { - const valueName = valueNames[i]!; + for (const [i, valueName] of valueNames.entries()) { const val = row.values?.[i]; rowData[valueName] = val ? getMetricValue(val) : null; }
diff --git a/ui/src/plugins/dev.perfetto.TimelineSync/index.ts b/ui/src/plugins/dev.perfetto.TimelineSync/index.ts index 3042503..5b69bbd 100644 --- a/ui/src/plugins/dev.perfetto.TimelineSync/index.ts +++ b/ui/src/plugins/dev.perfetto.TimelineSync/index.ts
@@ -176,8 +176,8 @@ this.disableTimelineSync(this._sessionId); const selectedClients = new Array<ClientId>(); const sel = ensureExists(clientsSelect).selectedOptions; - for (let i = 0; i < sel.length; i++) { - const clientId = parseInt(sel[i]!.value); + for (const option of sel) { + const clientId = parseInt(option.value); if (!isNaN(clientId)) selectedClients.push(clientId); } selectedClients.push(this._clientId); // Always add ourselves.
diff --git a/ui/src/plugins/dev.perfetto.VideoFrames/video_frame_player.ts b/ui/src/plugins/dev.perfetto.VideoFrames/video_frame_player.ts index 7b2689c..4ee00f8 100644 --- a/ui/src/plugins/dev.perfetto.VideoFrames/video_frame_player.ts +++ b/ui/src/plugins/dev.perfetto.VideoFrames/video_frame_player.ts
@@ -243,8 +243,9 @@ error: (e) => console.warn('VideoFrames:', e), }); decoder.configure(decoderConfig(setup)); - for (let i = 0; i < range.length; i++) { - decoder.decode(chunkFor(setup, range[i]!, datas[i]!, i === 0)); + for (const [i, frame] of range.entries()) { + // `datas` is aligned with `range` (fetched from range's ids). + decoder.decode(chunkFor(setup, frame, datas[i]!, i === 0)); } await decoder.flush().catch(() => undefined); if (decoder.state !== 'closed') decoder.close(); @@ -421,12 +422,13 @@ const end = Math.min(base + FETCH_BATCH, this.frames.length); const batch = this.frames.slice(base, end); const datas = await this.fetchAuData(batch.map((f) => f.id)); - for (let i = 0; i < batch.length; i++) { + for (const [i, frame] of batch.entries()) { if (!(await this.waitForDecoderCapacity(token, session.decoder))) { return; } + // `datas` is aligned with `batch` (fetched from batch's ids). session.decoder.decode( - chunkFor(setup, batch[i]!, datas[i]!, base + i === k), + chunkFor(setup, frame, datas[i]!, base + i === k), ); } }
diff --git a/ui/src/plugins/org.chromium.ChromeScrollJank/scroll_delta_graph.ts b/ui/src/plugins/org.chromium.ChromeScrollJank/scroll_delta_graph.ts index b68e466..15ed625 100644 --- a/ui/src/plugins/org.chromium.ChromeScrollJank/scroll_delta_graph.ts +++ b/ui/src/plugins/org.chromium.ChromeScrollJank/scroll_delta_graph.ts
@@ -217,8 +217,7 @@ // Filter out the predictor deltas from the presented deltas, as these will be // rendered in a new layer, with new tooltip/color/etc. const filteredPresentedDeltas = presentedDeltas.filter((item) => { - for (let i = 0; i < predictorDeltas.length; i++) { - const predictorDelta: ScrollDeltaDetails = predictorDeltas[i]!; + for (const predictorDelta of predictorDeltas) { if ( predictorDelta.ts == item.ts && predictorDelta.scrollUpdateId == item.scrollUpdateId
diff --git a/ui/src/plugins/org.chromium.ChromeScrollJank/scroll_details_panel.ts b/ui/src/plugins/org.chromium.ChromeScrollJank/scroll_details_panel.ts index f84c685..6154b96 100644 --- a/ui/src/plugins/org.chromium.ChromeScrollJank/scroll_details_panel.ts +++ b/ui/src/plugins/org.chromium.ChromeScrollJank/scroll_details_panel.ts
@@ -243,14 +243,15 @@ jankIntervals, ); - if (presentedDeltas.length > 0) { - this.metrics.startOffset = presentedDeltas[0]!.scrollOffset; - this.metrics.endOffset = - presentedDeltas[presentedDeltas.length - 1]!.scrollOffset; + const firstDelta = presentedDeltas[0]; + const lastDelta = presentedDeltas[presentedDeltas.length - 1]; + if (firstDelta !== undefined && lastDelta !== undefined) { + this.metrics.startOffset = firstDelta.scrollOffset; + this.metrics.endOffset = lastDelta.scrollOffset; let pixelsScrolled = 0; - for (let i = 0; i < presentedDeltas.length; i++) { - pixelsScrolled += Math.abs(presentedDeltas[i]!.scrollDelta); + for (const delta of presentedDeltas) { + pixelsScrolled += Math.abs(delta.scrollDelta); } if (pixelsScrolled != 0) {
diff --git a/ui/src/trace_processor/query_result_benchmark_unittest.ts b/ui/src/trace_processor/query_result_benchmark_unittest.ts index 0171bea9..e2ea6d5 100644 --- a/ui/src/trace_processor/query_result_benchmark_unittest.ts +++ b/ui/src/trace_processor/query_result_benchmark_unittest.ts
@@ -78,7 +78,7 @@ function pushLenDelim(arr: number[], field: number, payload: number[]): void { pushTag(arr, field, 2); pushVarint(arr, payload.length); - for (let i = 0; i < payload.length; i++) arr.push(payload[i]!); + arr.push(...payload); } const textEncoder = new TextEncoder();
diff --git a/ui/src/widgets/flamegraph.ts b/ui/src/widgets/flamegraph.ts index b476bfb..86aa07e 100644 --- a/ui/src/widgets/flamegraph.ts +++ b/ui/src/widgets/flamegraph.ts
@@ -1214,6 +1214,8 @@ }); const zoomQueryWidth = zoomRegion.queryXEnd - zoomRegion.queryXStart; + // Hot path (all nodes, on every redraw): indexed iteration avoids the + // per-iteration pair allocation of `.entries()`. `i` is provably in range. for (let i = 0; i < nodes.length; i++) { const {id, parentId, depth, xStart: qXStart, xEnd: qXEnd} = nodes[i]!; assertTrue(depth !== 0);
diff --git a/ui/src/widgets/tree_explorer.ts b/ui/src/widgets/tree_explorer.ts index 9713830..c8ecf43 100644 --- a/ui/src/widgets/tree_explorer.ts +++ b/ui/src/widgets/tree_explorer.ts
@@ -375,8 +375,7 @@ // Split text at those positions const result: string[] = []; - for (let i = 0; i < splitPositions.length; i++) { - const start = splitPositions[i]!; + for (const [i, start] of splitPositions.entries()) { const end = splitPositions[i + 1] ?? text.length; const part = text.substring(start, end).trim(); if (part) {