Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

Unity3d에서 transform을 변수에 할당해 사용하는 특별한 이유가 있을까요?

아래와 같은 질문이 있군요. ^^

[질문] Unity3d에서 transform을 변수에 할당해 사용하는 특별한 이유가 있을까요? 
; http://www.gamecodi.com/board/zboard.php?id=GAMECODI_Talkdev&no=2891&z=10

보통의 Unity3d 소스 코드에서 다음과 같이 코딩을 하는 것이 관례인데요.

using UnityEngine;

public class PlayerCtrl : MonoBehaviour 
{
    Transform tr;

    void Start () 
    {
        tr = this.transform;
        // 또는
        // tr = GetComponent<Transform>();
    }
    
    void Update () 
    {
    }
}

질문의 요지는, 과연 this.transform의 필드처럼 보이는 값을 tr 필드에 담아두는 것이 얼마나 속도 향상이 있을까라는 의문입니다. 사실 필드는 물론이고 프로퍼티를 사용했다 하더라도 일반적인 경우라면 거의 속도 차이가 없습니다. 이에 대해서는 전에 다음의 글에서 설명을 했었지요. ^^

C# - 프로퍼티로 정의하면 필드보다 느릴까요?
; https://www.sysnet.pe.kr/2/0/1545

C# - 프로퍼티로 정의하면 필드보다 느릴까요? - windbg / ollydbg
; https://www.sysnet.pe.kr/2/0/1546

자, 그럼 tr.transform은 어떨까요? 정확한 답은 ^^ .NET Reflector의 도움을 받으면 금방 알 수 있습니다.

우선, tr.transform은 예상과는 달리 UnityEngine.dll에 정의된 것을 보면 필드가 아닌 get property입니다.

public Transform transform
{
    get
    {
        return this.InternalGetTransform();
    }
}

또한 InternalGetTransform은 내부적으로 native API로 직접 연결되어 있습니다.

[MethodImpl(MethodImplOptions.InternalCall), WrapperlessIcall]
internal extern Transform InternalGetTransform();

즉, this.transform을 호출할 때마다 매번 Managed에서 Native로의 실행 환경이 전환되는 것입니다. (모노는 모르겠지만,) 닷넷 실행 환경에서는 분명히 이 작업에 비용이 듭니다. 게다가 InternalGetTransform 안에서의 구현이 어떻게 되어 있는지 알 수 없으므로, 어쨌든 이 경우에 개발자 코드에서 보관해 놓고 사용하는 것이 성능 향상에 도움이 됩니다.

그런데, "[질문] Unity3d에서 transform을 변수에 할당해 사용하는 특별한 이유가 있을까요? " 글의 덧글에 보면 최신 버전의 유니티에서는 필드 보관을 하지 않아도 된다고, 크게 성능 차이가 없다고 합니다.

확인을 위해 최신의 Unity 4.5.4f1 Free 버전을 다운로드 받아 UnityEngine.dll을 살펴봤는데, InternalGetTransform을 호출하는 구조까지 동일했습니다. 달리 말하면 여전히 Managed -> Native로의 부하는 있겠지만, 유니티 측에서 InternalGetTransform 내부의 구조를 개선했다고 봐야 할 것입니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 10/20/2015]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12415정성태11/18/202017439.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202019619VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202018566.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202020710.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202017479오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202017641디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202019472.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202034712도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202019849.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202020820.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202018723.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202019343.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202018219.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202019741.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202018984VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202015196오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202018712.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202018255오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202018278.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/202015276VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/202018081오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/202015702오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/202015340오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202019876.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202019558디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202018725.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...