StartCoroutine의 가비지
코루틴을 사용하는 경우
StartCoroutine를 호출하는 순간 해당 코루틴을 관리하기 위한 인스턴스가 생성되는데
이 인스턴스가 가비지로 이어질 수 있다.
StartCouroutine은 유니티 엔진 내부 코드이기 때문에 최적화 하기는 어려우므로
이로 인한 가비지 생성을 최소화 하기 위해서는 StartCoroutine을 최소한으로 사용해야 한다.
YieldInstruction의 가비지
YieldInstruction은 코루틴 내부의 yield 구문에서 사용되는 값으로
WaitForEndOfFrame
WaitForFixedUpdate
WaitForSeconds
등이 있는데 아래처럼 new를 통해 인스턴스화 될 때 가비지를 생성하게 된다.
yield return new WaitForEndOfFrame();
이때 생성되는 가비지를 최소화 하기 위해서
YieldInstruction을 캐싱하는 방법을 발견해서 적용했다.
우리 프로젝트에서는 아래 부분은 필요 없어서 쓰지 않았고
private static readonly Dictionary<float, WaitForSecondsRealtime> _timeIntervalReal
= new Dictionary<float, WaitForSecondsRealtime>(new FloatComparer());
public static WaitForSecondsRealtime WaitForSecondsRealTime(float seconds)
{
WaitForSecondsRealtime wfsReal;
if (!_timeIntervalReal.TryGetValue(seconds, out wfsReal))
_timeIntervalReal.Add(seconds, wfsReal = new WaitForSecondsRealtime(seconds));
return wfsReal;
}
이렇게만 클래스를 작성해 주었다.
public class YieldCache
{
class FloatComparer : IEqualityComparer<float>
{
bool IEqualityComparer<float>.Equals(float x, float y)
{
return x == y;
}
int IEqualityComparer<float>.GetHashCode(float obj)
{
return obj.GetHashCode();
}
}
public static readonly WaitForEndOfFrame WaitForEndOfFrame = new WaitForEndOfFrame();
public static readonly WaitForFixedUpdate WaitForFixedUpdate = new WaitForFixedUpdate();
private static readonly Dictionary<float, WaitForSeconds> _timeInterval
= new Dictionary<float, WaitForSeconds>(new FloatComparer());
public static WaitForSeconds WaitForSeconds(float seconds)
{
WaitForSeconds wfs;
if (!_timeInterval.TryGetValue(seconds, out wfs))
_timeInterval.Add(seconds, wfs = new WaitForSeconds(seconds));
return wfs;
}
}
이제 코루틴 메서드 안에서 프레임을 넘길 때
1번처럼 작성하던 것을 2번처럼 작성하면 가비지를 최소화 할 수 있다.
yield return new WaitForSeconds(0.38f); //1
yield return YieldCache.WaitForSeconds(0.38f); //2'Unity > 기타' 카테고리의 다른 글
| GPGS 사용해보기 (0) | 2023.04.20 |
|---|---|
| 안드로이드에서 드래그를 통한 카메라 줌인, 줌아웃 구현 (0) | 2023.03.19 |
| 스크린샷 기능 구현 (0) | 2023.03.15 |
| CardboardVR (0) | 2023.03.05 |
| 스프라이트 아틀라스(Sprite Atlas) (0) | 2023.02.13 |