Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[v3.8.6] Use array.forEach instead of for of to optimize code size #18112

Merged
merged 12 commits into from
Jan 10, 2025
9 changes: 1 addition & 8 deletions cocos/2d/assembler/label/text-processing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,14 +389,7 @@ export class TextProcessing {
}

private _calculateParagraphLength (paragraphedStrings: string[], ctx: CanvasRenderingContext2D, fontDesc: string): number[] {
const paragraphLength: number[] = [];

for (const para of paragraphedStrings) {
const width: number = safeMeasureText(ctx, para, fontDesc);
paragraphLength.push(width);
}

return paragraphLength;
return paragraphedStrings.map((para) => safeMeasureText(ctx, para, fontDesc));
}

private _updatePaddingRect (style: TextStyle, outputLayoutData: TextOutputLayoutData): void {
Expand Down
6 changes: 1 addition & 5 deletions cocos/2d/assembler/sprite/bar-filled.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,11 +199,7 @@ export const barFilled: IAssembler = {
renderData.chunk.setIndexBuffer(QUAD_INDICES);

// not need
const dataList = renderData.data;
for (const data of dataList) {
data.z = 0;
}

renderData.data.forEach((data) => { data.z = 0; });
return renderData;
},

Expand Down
14 changes: 11 additions & 3 deletions cocos/2d/assembler/sprite/radial-filled.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,15 @@ const _center = new Vec2();
const _triangles: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
let QUAD_INDICES: Uint16Array | null = null;

function _calcIntersectedPoints (left, right, bottom, top, center: Vec2, angle: number, intersectPoints: Vec2[]): void {
function _calcIntersectedPoints (
left: number,
right: number,
bottom: number,
top: number,
center: Vec2,
angle: number,
intersectPoints: Vec2[],
): void {
// left bottom, right, top
let sinAngle = Math.sin(angle);
sinAngle = Math.abs(sinAngle) > EPSILON ? sinAngle : 0;
Expand Down Expand Up @@ -112,9 +120,9 @@ function _calculateVertices (sprite: Sprite): void {
_vertPos[0].y = _vertPos[1].y = b;
_vertPos[2].y = _vertPos[3].y = t;

for (const num of _triangles) {
_triangles.forEach((num) => {
Vec2.set(num, 0, 0);
}
});

if (cx !== vertices[0]) {
Vec2.set(_triangles[0], 3, 0);
Expand Down
2 changes: 1 addition & 1 deletion cocos/2d/assets/bitmap-font.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export class FontAtlas {

public cloneLetterDefinition (): ILetterDefinition {
const copyLetterDefinitions: ILetterDefinition = {};
for (const key of Object.keys(this.letterDefinitions)) {
for (const key in this.letterDefinitions) {
minggo marked this conversation as resolved.
Show resolved Hide resolved
const value = new FontLetterDefinition();
js.mixin(value, this.letterDefinitions[key]);
copyLetterDefinitions[key] = value;
Expand Down
4 changes: 2 additions & 2 deletions cocos/2d/assets/sprite-atlas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export class SpriteAtlas extends Asset {
const frames: Array<SpriteFrame | null> = [];
const spriteFrames = this.spriteFrames;

for (const key of Object.keys(spriteFrames)) {
for (const key in spriteFrames) {
minggo marked this conversation as resolved.
Show resolved Hide resolved
frames.push(spriteFrames[key]);
}

Expand All @@ -114,7 +114,7 @@ export class SpriteAtlas extends Asset {
public _serialize (ctxForExporting: any): any {
if (EDITOR || TEST) {
const frames: string[] = [];
for (const key of Object.keys(this.spriteFrames)) {
for (const key in this.spriteFrames) {
const spriteFrame = this.spriteFrames[key];
let id = spriteFrame ? spriteFrame._uuid : '';
if (id && ctxForExporting && ctxForExporting._compressUuid) {
Expand Down
12 changes: 6 additions & 6 deletions cocos/2d/components/rich-text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -547,14 +547,14 @@ export class RichText extends Component {
}

public onDestroy (): void {
for (const seg of this._segments) {
this._segments.forEach((seg) => {
seg.node.removeFromParent();
if (seg.type === RichTextChildName) {
labelPool.put(seg);
} else if (seg.type === RichTextChildImageName) {
imagePool.put(seg);
}
}
});

this.node.off(NodeEventType.ANCHOR_CHANGED, this._updateRichTextPosition, this);
this.node.off(NodeEventType.LAYER_CHANGED, this._applyLayer, this);
Expand Down Expand Up @@ -766,7 +766,7 @@ export class RichText extends Component {
protected _onTouchEnded (event: EventTouch): void {
const components = this.node.getComponents(Component);

for (const seg of this._segments) {
this._segments.forEach((seg) => {
const clickHandler = seg.clickHandler;
const clickParam = seg.clickParam;
if (clickHandler && this._containsTouchLocation(seg, event.touch!.getUILocation())) {
Expand All @@ -778,7 +778,7 @@ export class RichText extends Component {
});
event.propagationStopped = true;
}
}
});
}

protected _containsTouchLocation (label: ISegment, point: Vec2): boolean {
Expand Down Expand Up @@ -1330,9 +1330,9 @@ this._measureText(styleIndex) as unknown as (s: string) => number,
}

protected _applyLayer (): void {
for (const seg of this._segments) {
this._segments.forEach((seg) => {
seg.node.layer = this.node.layer;
}
});
}

protected _resetLabelState (label: Label): void {
Expand Down
14 changes: 8 additions & 6 deletions cocos/3d/assets/mesh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -458,8 +458,9 @@ export class Mesh extends Asset {
const attributes: Attribute[] = [];
for (let k = 0; k < primitive.vertexBundelIndices.length; k++) {
const idx = primitive.vertexBundelIndices[k];
const vertexBundle = this._struct.vertexBundles[idx];
for (const attr of vertexBundle.attributes) {
const attributes = this._struct.vertexBundles[idx].attributes;
for (let j = 0; j < attributes.length; j++) {
const attr = attributes[j];
const attribute = new Attribute();
attribute.copy(attr);
attributes.push(attribute);
Expand Down Expand Up @@ -657,13 +658,13 @@ export class Mesh extends Asset {

const subMin = new Vec3();
const subMax = new Vec3();
for (const bound of dynamic.bounds) {
dynamic.bounds.forEach((bound) => {
if (bound) {
bound.getBoundary(subMin, subMax);
Vec3.min(minPos, subMin, minPos);
Vec3.max(maxPos, subMax, maxPos);
}
}
});

this._struct.minPosition = new Vec3(minPos.x, minPos.y, minPos.z);
this._struct.maxPosition = new Vec3(maxPos.x, maxPos.y, maxPos.z);
Expand Down Expand Up @@ -1310,8 +1311,9 @@ export class Mesh extends Asset {
if (primitiveIndex >= this._struct.primitives.length) {
return;
}
const primitive = this._struct.primitives[primitiveIndex];
for (const vertexBundleIndex of primitive.vertexBundelIndices) {
const vertexBundelIndices = this._struct.primitives[primitiveIndex].vertexBundelIndices;
for (let i = 0; i < vertexBundelIndices.length; i++) {
const vertexBundleIndex = vertexBundelIndices[i];
const vertexBundle = this._struct.vertexBundles[vertexBundleIndex];
const iAttribute = vertexBundle.attributes.findIndex((a) => a.name === (attributeName as string));
if (iAttribute < 0) {
Expand Down
16 changes: 9 additions & 7 deletions cocos/3d/assets/morph-rendering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,9 @@ export class StdMorphRendering implements MorphRendering {
},

destroy: (): void => {
for (const subMeshInstance of subMeshInstances) {
subMeshInstance?.destroy();
}
subMeshInstances.forEach((subMeshInstance) => {
if (subMeshInstance) subMeshInstance.destroy();
});
},
};
}
Expand Down Expand Up @@ -289,9 +289,9 @@ class GpuComputing implements SubMeshMorphRendering {
}

public destroy (): void {
for (const attribute of this._attributes) {
this._attributes.forEach((attribute) => {
attribute.morphTexture.destroy();
}
});
}

public createInstance (): {
Expand All @@ -313,7 +313,8 @@ class GpuComputing implements SubMeshMorphRendering {
requiredPatches: (): IMacroPatch[] => [{ name: 'CC_MORPH_TARGET_USE_TEXTURE', value: true }],

adaptPipelineState: (descriptorSet: DescriptorSet): void => {
for (const attribute of this._attributes) {
for (let i = 0; i < this._attributes.length; ++i) {
const attribute = this._attributes[i];
let binding: number | undefined;
switch (attribute.name) {
case AttributeName.ATTR_POSITION: binding = UNIFORM_POSITION_MORPH_TEXTURE_BINDING; break;
Expand Down Expand Up @@ -451,7 +452,8 @@ class CpuComputingRenderingInstance implements SubMeshMorphRenderingInstance {
}

public adaptPipelineState (descriptorSet: DescriptorSet): void {
for (const attribute of this._attributes) {
for (let i = 0; i < this._attributes.length; ++i) {
const attribute = this._attributes[i];
const attributeName = attribute.attributeName;
let binding: number | undefined;
switch (attributeName) {
Expand Down
17 changes: 13 additions & 4 deletions cocos/3d/misc/buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,12 @@
}
}
export function readBuffer (
target: DataView, format: Format = Format.R32F, offset = 0,
length: number = target.byteLength - offset, stride = 0, out: number[] = [],
target: DataView,
format: Format = Format.R32F,
offset = 0,
length: number = target.byteLength - offset,
stride = 0,
out: number[] = [],
): number[] {
const info = FormatInfos[format];
if (!stride) { stride = info.size; }
Expand All @@ -78,8 +82,13 @@
return out;
}
export function mapBuffer (
target: DataView, callback: (cur: number, idx: number, view: DataView) => number, format: Format = Format.R32F,
offset = 0, length: number = target.byteLength - offset, stride = 0, out?: DataView,
target: DataView,
callback: (cur: number, idx: number, view: DataView) => number,
format: Format = Format.R32F,

Check failure on line 87 in cocos/3d/misc/buffer.ts

View workflow job for this annotation

GitHub Actions / Run ESLint

Default parameters should be last
offset = 0,

Check failure on line 88 in cocos/3d/misc/buffer.ts

View workflow job for this annotation

GitHub Actions / Run ESLint

Default parameters should be last
length: number = target.byteLength - offset,

Check failure on line 89 in cocos/3d/misc/buffer.ts

View workflow job for this annotation

GitHub Actions / Run ESLint

Default parameters should be last
stride = 0,

Check failure on line 90 in cocos/3d/misc/buffer.ts

View workflow job for this annotation

GitHub Actions / Run ESLint

Default parameters should be last
out?: DataView,
): DataView {
if (!out) { out = new DataView(target.buffer.slice(target.byteOffset, target.byteOffset + target.byteLength)); }
const info = FormatInfos[format];
Expand All @@ -96,7 +105,7 @@
const y = x + componentBytesLength * iComponent;
const cur = target[reader](y, isLittleEndian);
// iComponent is usually more useful than y
out[writer](y, callback(cur, iComponent, target), isLittleEndian);

Check failure on line 108 in cocos/3d/misc/buffer.ts

View workflow job for this annotation

GitHub Actions / Run ESLint

Unsafe argument of type `any` assigned to a parameter of type `number`
}
}
return out;
Expand Down
39 changes: 7 additions & 32 deletions cocos/3d/misc/create-mesh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
if (positions.length > 0) {
attr = null;
if (geometry.attributes) {
for (const att of geometry.attributes) {
if (att.name === (AttributeName.ATTR_POSITION as string)) {
attr = att;
break;
}
}
attr = geometry.attributes.find((att) => att.name === AttributeName.ATTR_POSITION) || null;
}

if (!attr) {
Expand All @@ -77,12 +72,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
if (geometry.normals && geometry.normals.length > 0) {
attr = null;
if (geometry.attributes) {
for (const att of geometry.attributes) {
if (att.name === (AttributeName.ATTR_NORMAL as string)) {
attr = att;
break;
}
}
attr = geometry.attributes.find((att) => att.name === AttributeName.ATTR_NORMAL) || null;
}

if (!attr) {
Expand All @@ -99,12 +89,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
if (geometry.uvs && geometry.uvs.length > 0) {
attr = null;
if (geometry.attributes) {
for (const att of geometry.attributes) {
if (att.name === (AttributeName.ATTR_TEX_COORD as string)) {
attr = att;
break;
}
}
attr = geometry.attributes.find((att) => att.name === AttributeName.ATTR_TEX_COORD) || null;
}

if (!attr) {
Expand All @@ -121,12 +106,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
if (geometry.tangents && geometry.tangents.length > 0) {
attr = null;
if (geometry.attributes) {
for (const att of geometry.attributes) {
if (att.name === (AttributeName.ATTR_TANGENT as string)) {
attr = att;
break;
}
}
attr = geometry.attributes.find((att) => att.name === AttributeName.ATTR_TANGENT) || null;
}

if (!attr) {
Expand All @@ -143,12 +123,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
if (geometry.colors && geometry.colors.length > 0) {
attr = null;
if (geometry.attributes) {
for (const att of geometry.attributes) {
if (att.name === (AttributeName.ATTR_COLOR as string)) {
attr = att;
break;
}
}
attr = geometry.attributes.find((att) => att.name === AttributeName.ATTR_COLOR) || null;
}

if (!attr) {
Expand Down Expand Up @@ -179,9 +154,9 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
// Fill vertex buffer.
const vertexBuffer = new ArrayBuffer(vertCount * stride);
const vertexBufferView = new DataView(vertexBuffer);
for (const channel of channels) {
channels.forEach((channel) => {
writeBuffer(vertexBufferView, channel.data, channel.attribute.format, channel.offset, stride);
}
});
bufferBlob.setNextAlignment(0);
const vertexBundle: Mesh.IVertexBundle = {
attributes,
Expand Down
10 changes: 5 additions & 5 deletions cocos/3d/misc/read-mesh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,17 @@ export function readMesh (mesh: Mesh, iPrimitive = 0): IGeometry {
const dataView = new DataView(mesh.data.buffer, mesh.data.byteOffset, mesh.data.byteLength);
const struct = mesh.struct;
const primitive = struct.primitives[iPrimitive];
for (const idx of primitive.vertexBundelIndices) {
primitive.vertexBundelIndices.forEach((idx) => {
const bundle = struct.vertexBundles[idx];
let offset = bundle.view.offset;
const { length, stride } = bundle.view;
for (const attr of bundle.attributes) {
bundle.attributes.forEach((attr) => {
const name: AttributeName = _keyMap[attr.name];
if (name) { out[name] = (out[name] || []).concat(readBuffer(dataView, attr.format, offset, length, stride)); }
offset += FormatInfos[attr.format].size;
}
}
});
});
const view = primitive.indexView!;
out.indices = readBuffer(dataView, Format[`R${view.stride * 8}UI`], view.offset, view.length);
out.indices = readBuffer(dataView, Format[`R${view.stride * 8}UI`] as Format, view.offset, view.length);
return out;
}
6 changes: 3 additions & 3 deletions cocos/3d/skeletal-animation/skeletal-animation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ export class SkeletalAnimation extends Animation {
* @zh 重建动画并立即同步所有挂点的转换矩阵到它们的目标节点上。
*/
public rebuildSocketAnimations (): void {
for (const socket of this._sockets) {
this._sockets.forEach((socket) => {
const joint = this.node.getChildByPath(socket.path);
const { target } = socket;
if (joint && target) {
Expand All @@ -247,8 +247,8 @@ export class SkeletalAnimation extends Animation {
Mat4.fromRTS(m4_2, target.rotation, target.position, target.scale);
if (!Mat4.equals(m4_2, m4_1)) { target.matrix = m4_1; }
}
}
for (const stateName of Object.keys(this._nameToState)) {
});
for (const stateName in this._nameToState) {
const state = this._nameToState[stateName] as SkeletalAnimationState;
state.rebuildSocketCurves(this._sockets);
}
Expand Down
8 changes: 4 additions & 4 deletions cocos/animation/animation-component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,17 @@ export class Animation extends Eventify(Component) {
this._crossFade.clear();
}
// Remove state for old automatic clips.
for (const clip of this._clips) {
this._clips.forEach((clip) => {
if (clip) {
this._removeStateOfAutomaticClip(clip);
}
}
});
// Create state for new clips.
for (const clip of value) {
value.forEach((clip) => {
if (clip) {
this.createState(clip);
}
}
});
// Default clip should be in the list of automatic clips.
const newDefaultClip = value.find((clip) => equalClips(clip, this._defaultClip));
if (newDefaultClip) {
Expand Down
Loading
Loading