(二)Unity5.0新特性------unity內部:記憶體 和 效能(以及Unity5的升級最佳化),unity5

來源:互聯網
上載者:User

(二)Unity5.0新特性------unity內部:記憶體 和 效能(以及Unity5的升級最佳化),unity5

      我們的指令碼代碼裡經常會需要訪問gameObject引用或者某個組件的引用,最好的方式當然是在指令碼Awake的時候就把這些可能訪問的東西都緩衝下來;如果需要訪問臨時gameObject執行個體的某屬性或者臨時某組件的gameObject執行個體,在能夠確保組件一定存在(可以使用[RequireComponent( typeof(AudioSource ))] 如果沒有自動添加移除不了!)的情況下,可以用屬性訪問,畢竟屬性訪問比GetComponent要快上一倍,但是如果不能確定組件是否存在,甚至是需要對組件的存在性做判斷時,一定不要用對屬性訪問結果判空的方式,而要用GetComponent,這裡面節省的開銷不是一點半點鐘。       而在unity5中你是沒得選擇了,因為沒有了屬性訪問器。 看看的 GameObject類的對比。(4.6和5.0版本)     
unity內部:記憶體 和 效能Topics
• Memory Overview
• Garbage Collection
• Mesh Internals
• Scripting
• Job System一、 Memory OverviewMemory Domains記憶體域
• Native (internal)本地 (內部)
• Asset Data: Textures, AudioClips, Meshes
• Game Objects & Components: Transform, etc..
• Engine Internals: Managers, Rendering, Physics, etc..
• Managed - Mono
• Script objects (Managed dlls)
• Wrappers (封裝類)for Unity objects: Game objects, assets,components• Native Dlls
• User’s dlls and external dlls (for example: DirectX)

Native Memory: Internal Allocators本機記憶體: 內部分配器
• Default
• GameObject
• Gfx 圖形和渲染相關
• Profiler事件探查器
               5.x: 在 Dll 中使用原生分配器公開的 API
Managed Memory託管的記憶體
• Value types實值型別 (bool, int, float, struct, ...)          • 在堆棧記憶體中存在。當從堆棧中移除時取消分配。沒有GC。• Reference types (classes) 參考型別 (類)

• 在堆上存在,當長時間不再被引用時都由mono/.net GC刪除。• 封裝為 Unity Objects :
• GameObject
• Assets : Texture2D, AudioClip, Mesh, …
• Components : MeshRenderer, Transform, MonoBehaviour
Mono Memory Internals
• Allocates system heap blocks for internal allocator(為內部分配器分配系統堆塊)
• Will allocate new heap blocks when needed( 在需要時將分配新的堆塊)
• Heap blocks are kept in Mono for later use( 堆塊保持在Mono中以後使用)
• Memory can be given back to the system after a while( 當過一段時間記憶體可以被交還給系統)•......但是它取決於平台è ,別指望它
• Garbage collector cleans up(記憶體回收行程清理)
• Fragmentation can cause new heap blocks even though memory is not exhausted(片段可以導致新的堆塊,即使記憶體不耗盡)
二、Garbage Collection Unity Object wrapper(封裝)• Some Objects used in scripts have large native backing memory in unity(在unity中在指令碼中被使用的一些對象有大批的本機支援記憶體)
• 直到運行Finalizers終結器記憶體才會釋放

Mono Garbage Collection•  GC.Collect
• Runs on the main thread when(運行在主線程上當:
• Mono exhausts the heap space( Mono耗盡堆空間)
• Or user calls System.GC.Collect()(或使用者調用 System.GC.Collect())
•  Finalizers終結器
     • Run on a separate thread(運行在一個單獨的線程上當:
• Controlled by mono(由mono控制• Can have several seconds delay(可以有幾秒鐘的延遲
•  Unity native memory(unity本機記憶體
• Dispose() cleans up internal memory(Dispose () 清理內部記憶體
• Eventually called from finalizer( 最終從finalizer終結器調用
• Manually call Dispose() to cleanup(手動調用 Dispose() 清理
Garbage Collection
• Roots are not collected in a GC.Collect(在GC.Collect上Roots不會被收集)
• Thread stacks(線程堆棧)• CPU Registers(CPU 寄存器)• GC Handles (used by Unity to hold onto managed objects) GC 控制代碼 (使用Unity來守住託管對象)• 靜態變數 !!
• Collection的時間尺度與託管的堆的大小
• 您分配的越多,gets變得越慢

GC: Best Practices 最佳做法
• Reuse objects . Use object pools(重用對象,使用對象池)
• 更喜歡基於堆棧的分配。使用結構而不是類
• System.GC.Collect 可以用於觸發collection
• 手動調用 Dispose立即清理
Avoid temp allocations避免臨時分配
• Don’t use FindObjects or LINQ
• Use StringBuilder for string concatenation
• Reuse large temporary work buffers(重用大量臨時工作緩衝區)
• ToString()
• .tag 改用 CompareTag() 方法

Unity API Temporary Allocations(臨時分配)
一些例子:
• GetComponents<T>
• Vector3[] Mesh.vertices
• Camera[] Camera.allCameras
• foreach
•  does not allocate by definition(定義不會分配)•  However, there can be a small allocation, depending on the implementation of .GetEnumerator()• 然而,根據具體的.GetEnumerator()實現可能會有 small有小的分配
5.x: 正在研究新的非分配non-allocating版本
Memory fragmentation記憶體片段
• Memory fragmentation is hard to account for(記憶體片段很難解釋)
• Fully unload dynamically allocated content(完全卸載動態分配內容)• 切換到一個空白情境,在next level之前
• This scene could have a hook where you may pause the game long enough to sample if there is anything significant in memory
• Ensure you clear out variables so GC.Collect will remove as much as possible
• 確保你clear變數,GC.Collect將刪除儘可能多地• 儘可能避免分配
• 重用對象儘可能在scene play下
• Clear them out for map load to clean the memory(把它們清理乾淨memory的地圖載入)
Unloading Unused Assets卸載未使用的資產
• Resources.UnloadUnusedAssets 將觸發資產記憶體回收
•他是搜尋所有unreferenced assets 和卸載他們•他是一個async operation非同步作業的 • 它loading 一個 level後在內部被調用
• Resources.UnloadAsset 是最好的
• 您需要知道到底您需要Unload卸載什麼•Unity而不必全部掃描
• Unity 5.0: 多線程的asset記憶體回收
三、Mesh Internals Mesh Read/Write Option
• 它允許您在運行時修改mesh• 如果啟用enabled, Mesh的系統副本會保留在記憶體中• enabled是預設
• 在某些情況下,禁用此選項不會減少記憶體使用量量
• Skinned meshes皮膚網格• iOS
Unity 5.0: disable by default預設情況下是禁用 – under consideration
Non-Uniform scaled Meshes非均勻縮放網格
我們需要正確轉換的頂點法線
• Unity 4.x:
• 在 CPU 上變換transform網格mesh• 建立資料的額外副本
• Unity 5.0
• 在 GPU 上縮放Scaled• 不再需要額外的記憶體
Static Batching這是什嗎?
• 它是最佳化,減少了draw calls 和狀態改變的數量他如何使用?
• 在player settings + Tag對象為static。如下:
它內部如何工作?
• Build-time 產生時間: Vertices are transformed to world- space頂點轉換為世界空間• Run-time已耗用時間: Index buffer is created with indices of visible objects索引緩衝建立與指數的可見對象Unity 5.0:
• Re-implemented static batching without copying of index buffers重新實施靜態配料而不複製索引緩衝 Dynamic Batching這是什嗎?
• 類似於靜態配料,在運行時對象是non-static
他如何使用?
• 在player settings• no need to tag. it auto-magically works…無需標記。它自動神奇地工作......它內部如何工作?
• objects are transformed to world space on the對象轉換到世界空間上
CPU
• 建立臨時的 VB & IB
• 在一個draw call 中呈現Rendered Unity 5.x:  我們正在考慮使每個平台參數

Mesh Skinning
根據平台的不同實現:
• x86: SSE
• iOS/Android/WP8: Neon optimizations
• D3D11/XBoxOne/GLES3.0: GPU
• XBox360, WiiU: GPU (memexport)
• PS3: SPU
• WiiU: GPU w/ stream out
Unity 5.0: Skinned meshes 通過共用執行個體之間的索引緩衝使用較少的記憶體
四、Scripting(重要!) Unity 5.0: Mono• No upgrade不能升級
• Mainly bug fixes主要 bug 修複
• New tech in WebGL: IL2CPP新科技在 WebGL: IL2CPP
• http://blogs.unity3d.com/2014/04/29/on-the-future-of-web-publishing-in-unity/
• 敬請: 會有關於它的部落格文章 GetComponent<T>       
它要求遊戲物體,得到一個指定類型的組件:
• The GO contains a list of Components
• GO包含Components組件的列表• 每個組件類型被比作 T
• 第一個組件的類型 T (或從 T 派生),將返回給調用方
• 不太多的開銷,但它仍然需要調入機器碼 Unity 5.0: Property Accessors屬性的訪問器
• 大多數accessors將在Unity 5.0中被移除• 目的是減少依賴,因此提高模組化
• Transform將仍然被保留• 現有的指令碼將被轉換。樣本:in 5.0:
Transform Component
• this.transform 是和 GetComponent<Transform>() 一樣
•  transform.position/rotation 需要:
• find Transform component• Traverse hierarchy to calculate absolute position遍曆階層來計算絕對位置• Apply translation/rotation
•  transform internally stores the position relative to the parent變換在內部儲存的位置是相對於父級
• transform.localPosition = new Vector(…) →  簡單的賦值• transform.position = new Vector(…)→  costs the same if no father, otherwise it will need to traverse the hierarchy up to transform the abs position into local• transform.position = 新的 Vector(...)→  如果沒有父親代價是一樣的,否則它將需要本地遍曆hierarchy得到transform的位置絕對值
• 最後,將通過messages通知其他組件 (對撞機、 剛體、 輕型、 相機、)。
Instantiate
API:
• Object Instantiate(Object, Vector3, Quaternion);• Object Instantiate(Object);
Implementation執行:
• 複製GameObject Hierarchy and Components• Copy Properties複製屬性• Awake• Apply new Transform (if provided)適用新的變換 (如果提供)
Instantiate cont..ed
• Awake 可以是昂貴的
• AwakeFromLoad (主線程)
• clear states清理狀態• internal state caching內部狀態緩衝• pre-compute預先計算
Unity 5.0:
• Allocations have been reduced分配已被減少• 一些內部的迴圈,用於複製的資料進行了最佳化
JIT Compilation( JIT 編譯)
這是什嗎?
• 在進程中從 CIL 代碼產生機器代碼,在應用程式運行期間
Pros:優點:
• 為當前平台,它產生最佳化的代碼Cons:缺點:
•  Each time a method is called for the first time, the application will suffer a certain performance penalty because of the compilation
• 每次方法被第一次調用時,應用程式因為彙編將受到某些效能處罰  JIT compilation spikes
pre-JITting怎麼樣?• RuntimeHelpers.PrepareMethod 是行不通的:
....MethodHandle.GetFunctionPointer() 比較好
五、Job System Unity 5.0: Job System (internal)
job system的目標:• 基於多線程的代碼 可以很容易地寫得很高效率的工作• The jobs should be able to run safely in parallel to script code
• jobs工作應該能夠安全地平行的運行指令碼代碼 Job System: 它是什麼 ?• 它是一個Framework架構,我們打算在現有的和新的子系統中使用的• 我們想要Animation, NavMesh, Occlusion, Rendering,等等儘可能多的並行運行• 這最終將導致更好的效能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.