---
title: 优化数组
product: Unity Editor
version: '6000.0'
latest_version: '7000.0'
status: This page documents version 6000.0. The latest version is 7000.0.
canonical: https://docs.unity.com/zh-cn/engine/6000.0/manual/scripting/optimization/performance-optimizing-code-managed-memory/arrays
latest_url: https://docs.unity.com/zh-cn/engine/7000.0/manual/scripting/optimization/performance-optimizing-code-managed-memory/arrays.md
generated_at: 2026-11-16T08:43:16.443Z
locale: zh-cn
---

# 优化数组

> 优化 When 和如何在代码中使用数组。

以下 Page Outlines 示例用于提高使用[数组](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/arrays)时的代码性能。

## 将数组作为Parameters传通道方法##pass-arrays-as-parameters-to-methods

有时，编写一个创建新建Array、用值填充数Array后返回数组的方法可能很方便。但是，如果反复调用此方法，则时间都会分配新建内存。

以下示例代码显示了每次调用时间都会创建Array的方法示例：

```lang-cs
// Bad C# script example: Every time the RandomList method is called it
// allocates a new array
using UnityEngine;
using System.Collections;

public class ExampleScript :MonoBehaviour {
    浮点[] RandomList(整型 numElements) {
        var result = new float[numElements];
        
        for (int i = 0; i < numElements; i++) {
            result[i] = Random.value;
        }
        
        return result;
    }
}
```

避免每次都分配内存的一种方法是 make 使用 Array 为引用类型这一事实。您可以修改作为参数传递给方法的 Array，结果在方法返回后保留。为此，您可以按如下方式配置示例代码：

```lang-cs
// Good C# script example: This version of method is passed an array to fill
// with random values.可以缓存和重用 Array 以避免重复
// temporary allocations
using UnityEngine;
using System.Collections;

public class ExampleScript :MonoBehaviour {
    void RandomList(float[] arrayToFill) {
        for (int i = 0; i < arrayToFill.Length; i++) {
            arrayToFill[i] = Random.value;
        }
    }
}
```

此代码将Array的现有内容替换为新建。此工作流程流程要求调用代码执行Array的初始分配，但调用该函数When不会GenerateAny新建的垃圾。然后，在下次调用此方法时，无需在 Managed 堆上进行任何新建分配，即可重用 Array 并使用随机数重新填充。

## 避免重复访问 Array 值的 Unity API##avoid-repeated-access-to-array-valued-unity-apis

数组意外分配的一个原因是重复访问返回数组的 Unity API。All返回数组的 Unity API 都会在时间创建一个Array的新建复制本。如果您的代码访问 Array 值的 Unity API 的频率超过需要，可能会影响应用程序的性能。

例如，以下代码在每个Loop迭代中创建顶点数Array的四个副本。每次访问 `.vertices` 属性时都会进行分配：

```lang-cs
// Bad C# script example: this loop create 4 copies of the vertices array per iteration
void Update() {
    for(int i = 0; i < mesh.vertices.Length; i++) {
        浮点 x, y, z;

        x = mesh.vertices[i].x;
        y = mesh.vertices[i].y;
        z = mesh.vertices[i].z;

        // ...

        DoSomething(x, y, z);   
    }
}
```

无论 Loop 迭代的数量如何，都可以将此代码重构为单一 Array 分配。为此，请将代码配置为在Loop之前捕获顶点数Array：

```lang-cs
// Better C# script example: create one copy of the vertices array
// and work with that
void Update() {
    var vertices = mesh.vertices;

    for(int i = 0; i < vertices.Length; i++) {

        浮点 x, y, z;

        x = vertices[i].x;
        y = vertices[i].y;
        z = vertices[i].z;

        // ...

        DoSomething(x, y, z);   
    }
}
```

实现此目的的最佳方法是保持一`List`顶点，这些顶点在帧之间缓存并重复使用，然后在需要时使用[`Mesh.GetVertices`](/engine/6000.0/script-reference/unityengine/mesh/getvertices.md)填充。

```lang-cs
// Best C# script example: create one copy of the vertices array
// and work with that.
列表<Vector3> m_vertices = 新建列表<Vector3>();

void Update() {
    mesh.GetVertices(m_vertices);

    for(int i = 0; i < m_vertices.Length; i++) {

        浮点 x, y, z;

        x = m_vertices[i].x;
        y = m_vertices[i].y;
        z = m_vertices[i].z;

        // ...

        DoSomething(x, y, z);   
    }
}
```

虽然访问分配一次Array的属性对 CPU 性能的影响并高，但Tight循环中的重复访问会创建 CPU 性能热点。重复访问会扩展 [Managed 堆](/engine/6000.0/manual/analysis/performance-memory/managed-memory/introduction.md)。

这个问题在移动端 Devices 上很常见，因为 [`Input.touches`](/engine/6000.0/script-reference/unityengine/input/touches.md) API 的行为与前一个示例类似。项目通常还包含类似于以下的代码，每次访问 `.touches` 属性时都会发生分配：

```lang-cs
// Bad C# script example: Input.touches returns an array every time it’s accessed
for ( int i = 0; i < Input.touches.Length; i++ ) {
   Touch touch = Input.touches[i];

    // …
}
```

要改善这一点，可以配置代码以将Array分配提升出Loop条件：

```lang-cs
// Better C# script example: Input.touches is only accessed once here
Touch[] touch = 输入。touches;

for ( int i = 0; i < touches.Length; i++ ) {

   Touch touch = touches[i];

   // …
}
```

以下代码示例将前面的示例转换为无分配自由`Touch` API：

```lang-cs
// BEST C# script example: Input.touchCount and Input.GetTouch don’t allocate at all.
int touchCount = Input.touchCount;

for ( int i = 0; i < touchCount; i++ ) {
   Touch touch = Input.GetTouch(i);

   // …
}
```

> **Note:**
>
> 属性访问 (`Input.touchCount`) 保持在 Loop 条件之外，以保存调用属性的 get 方法对 CPU 的影响。

### 其他非分配 API##alternative-non-allocating-apis

某些 Unity API 具有不会导致内存分配的替代版本。When可能使用这些。表包含分配 API 及其非分配替代方案的示例：

| **分配 API**                                                                                            | **非分配 API 替代方案**                                                                                            |
| ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| [`Physics.RaycastAll`](/engine/6000.0/script-reference/unityengine/physics/raycastall.md)             | [`Physics.RaycastNonAlloc`](/engine/6000.0/script-reference/unityengine/physics/raycastnonalloc.md)         |
| [`Animator.parameters`](/engine/6000.0/script-reference/unityengine/animator/parameters.md)           | 4 和 5                                                                                                       |
| [`Renderer.sharedMaterials`](/engine/6000.0/script-reference/unityengine/renderer/sharedmaterials.md) | [`Renderer.GetSharedMaterials`](/engine/6000.0/script-reference/unityengine/renderer/getsharedmaterials.md) |

General 中，如果 方法返回 Array，则通常有一个非分配 API 版本，您可以使用该版本将 Array 通道到该 API。

## 使用零长度数组的 Static 实例##use-static-instances-of-zero-length-arrays

当 Array 值方法需要返回空设置时，一些开发团队更喜欢返回空数组而不是 `null`。这种编码模式在许多 Managed 语言中都很常见，尤其是在 C# 和 Java 中。

从 方法返回零长度 Array 时，返回零长度 Array 的预分配 Static 实例比重复创建空对象数组更有效。

## 对大型数组使用原生数组或Other原生容器##use-native-arrays-or-other-native-containers-for-large-arrays

Unity 的[垃圾回收器](/engine/6000.0/manual/analysis/performance-memory/managed-memory/garbage-collector.md)是一种启发式垃圾回收器，这意味着它将具有指针大小的 Any Field 视为指针。垃圾回收器会检查遇到的每个指针和引用。

当您使用大型数组（超过 1 万个元素）时，垃圾回收器可能会将大型数组解释为需要检查的长串指针，这会增加内存压力并减慢垃圾回收器的速度。

脚本 VM 还必须为大型数组分配大块的 Managed 堆 Space，这会增加随机值在 Managed 堆块的内存地址范围内看起来像有效地址的可能性。大型数组也是托管堆碎片化的一个重要因素。

如果需要分配此类长度的数组，请考虑使用 Unity Core API 中的 `Unity.Collections` 命名空间（包括 [`NativeArray`](/engine/6000.0/script-reference/unity/collections/nativearray1.md)）中的 Collection 类型以及 [Unity Collections 包](https://docs.unity3d.com/Packages/com.unity.collections@latest)中的数据结构。另一个优点是，使用这些 Collections 与[任务 System](/engine/6000.0/manual/scripting/optimization/job-system.md) 兼容并爆发。

## 其他资源##additional-resources

* [托管内存简介](/engine/6000.0/manual/analysis/performance-memory/managed-memory/introduction.md)
* [参考类型管理](/engine/6000.0/manual/scripting/optimization/performance-optimizing-code-managed-memory/reference-types.md)
* [创建可重用代码](/engine/6000.0/manual/scripting/optimization/performance-optimizing-code-managed-memory/reusable-code.md)
