---
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/ko-kr/engine/6000.0/manual/scripting/optimization/performance-optimizing-code-managed-memory/arrays
latest_url: https://docs.unity.com/ko-kr/engine/7000.0/manual/scripting/optimization/performance-optimizing-code-managed-memory/arrays.md
generated_at: 2026-11-19T13:46:06.689Z
locale: ko-kr
---

# 배열 최적화

> 코드에서 배열을 사용하는 시기와 방법을 최적화합니다.

다음 페이지에서는 [배열](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/arrays)을 사용할 때 코드의 성능을 개선하는 예제를 간략하게 설명합니다.

## 배열을 메서드로 파라미터로 전달한다.##pass-arrays-as-parameters-to-methods

때로는 새로운 배열을 생성하고 배열을 값으로 채운 후 값을 반환하는 메서드를 작성하는 것이 편리할 수 있습니다. 하지만 이 메서드를 반복적으로 호출하면 매번 새로운 메모리가 할당됩니다.

다음 예제 코드는 호출될 때마다 배열을 만드는 메서드의 예제를 보여 줍니다.

```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 {
    float[] RandomList(int numElements) {
        var result = new float[numElements];
        
        for (int i = 0; i < numElements; i++) {
            result[i] = Random.value;
        }
        
        return result;
    }
}
```

매번 메모리 할당을 방지하는 한 가지 방법은 배열이 레퍼런스 유형이라는 사실을 활용하는 것입니다. 메서드에 파라미터로 전달되는 배열을 수정할 수 있으며, 메서드가 반환된 후 결과는 그대로 유지됩니다. 이를 위해 다음과 같이 예제 코드를 설정할 수 있습니다.

```lang-cs
// Good C# script example: This version of method is passed an array to fill
// with random values. 배열을 캐싱하고 재사용하여 반복되는 것을 방지할 수 있습니다.
// 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;
        }
    }
}
```

이 코드는 배열의 기존 콘텐츠를 새로운 값으로 대체합니다. 이 워크플로에서는 호출 코드가 배열의 초기 할당을 수행해야 하지만, 함수가 호출될 때 새로운 가비지를 생성하지 않습니다. 그런 다음 이 메서드가 다음에 관리되는 힙 새 할당 없이 호출될 때 배열을 재사용하고 무작위 숫자로 다시 채울 수 있습니다.

## 스토리지 기반 Unity API에 대한 반복 액세스 방지##avoid-repeated-access-to-array-valued-unity-apis

스토리지에 의도치 않은 할당의 원인 중 하나는 스토리지를 반환하는 Unity API에 반복적으로 액세스하는 것입니다. 배열을 반환하는 모든 Unity API는 액세스할 때마다 배열의 새 복사본을 생성합니다. 코드가 필요 이상으로 배열 값의 Unity API 액세스하는 경우 애플리케이션의 성능에 영향을 줄 수 있습니다.

예를 들어 다음 코드는 루프 반복당 4개의 버텍스 배열 사본을 생성합니다. 할당은 `.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++) {
        float x, y, z;

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

        // ...

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

루프 반복 횟수에 관계없이 이 코드를 단일 배열 할당으로 리팩터링할 수 있습니다. 이렇게 하려면 루프 전에 버텍스 배열을 캡처하도록 코드를 설정합니다.

```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++) {

        float 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++) {

        float x, y, z;

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

        // ...

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

배열을 한 번 할당하는 프로퍼티에 액세스하면 CPU 성능에 미치는 영향이 높지 않지만, 긴밀한 루프 내에서 반복 액세스하면 CPU 성능 핫스팟이 발생합니다. 반복 액세스는 [관리되는 hip](/engine/6000.0/manual/analysis/performance-memory/managed-memory/introduction.md) 를 확장합니다.

이 문제는 [`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];

    // …
}
```

이를 개선하기 위해 다음과 같이 코드를 설정하여 배열 할당을 루프 조건에서 벗어나도록 할 수 있습니다.

```lang-cs
// Better C# script example: Input.touches is only accessed once here
Touch[] touches = Input.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`)는 프로퍼티의 get 메서드를 호출할 때 발생하는 CPU 영향을 줄이기 위해 루프 상태 밖에 유지됩니다.

### 할당하지 않는 대체 API##alternative-non-allocating-apis

일부 Unity API에는 메모리 할당이 발생하지 않는 대체 버전이 있습니다. 가능하면 이를 사용해야 합니다. 다음 표에는 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) |

일반적으로 메서드가 배열을 반환하는 경우 일반적으로 배열을 전달하는 데 사용할 수 있는 할당이 없는 API 버전이 있습니다.

## 길이가 0인 배열의 정적 인스턴스 사용##use-static-instances-of-zero-length-arrays

일부 개발 팀은 배열 값 메서드가 빈 세트를 반환해야 할 때 `null` 대신 빈 배열을 반환하는 것을 선호합니다. 이 코딩 패턴은 특히 C# 및 Java와 같은 많은 관리 언어에서 흔히 사용됩니다.

메서드에서 길이가 0인 배열을 반환하는 경우, 길이가 0인 배열의 미리 할당된 정적 인스턴스를 반복적으로 빈 배열을 생성하는 것보다 효율적입니다.

## 대규모 배열에 네이티브 배열 또는 기타 네이티브 컨테이너 사용##use-native-arrays-or-other-native-containers-for-large-arrays

Unity의 [가비지 컬렉터](/engine/6000.0/manual/analysis/performance-memory/managed-memory/garbage-collector.md)는 후리틱 가비지 컬렉터로, 포인터 크기의 필드를 포인터처럼 취급합니다. 가비지 컬렉터 발견되는 모든 포인터와 레퍼런스를 확인합니다.

10천 개 이상의 요소가 포함된 대규모 배열을 사용하는 경우 가비지 컬렉터 대규모 배열을 확인해야 하는 긴 포인터 리스트로 해석할 수 있으므로 메모리 압박이 증가하고 가비지 컬렉터 속도가 느려집니다.

또한 스크립팅 VM은 대규모 배열에 대량의 관리되는 힙 공간을 할당해야 하므로 임의의 값이 관리되는 힙 청크의 메모리 주소 범위 내에서 유효한 주소처럼 보일 가능성이 증가합니다. 대규모 배열은 관리되는 힙 단편화에도 큰 영향을 미칩니다.

이러한 길이의 배열을 할당해야 하는 경우 Unity 코어 API의 `Unity.Collections` 네임스페이스([`NativeArray`](/engine/6000.0/script-reference/unity/collections/nativearray1.md) 포함)와 [Unity Collections 패키지](https://docs.unity3d.com/Packages/com.unity.collections@latest)의 데이터 구조를 사용하는 것이 좋습니다. 추가적인 이점으로, 이러한 Collections 사용은 [잡 시스템](/engine/6000.0/manual/scripting/optimization/job-system.md)과 Burst와 호환됩니다.

## 추가 리소스##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)
