SlideShare a Scribd company logo
1 of 26
Download to read offline
Memory profiling in Unity
Kim Steen Riber (kim@unity3d.com)
Page
Who am I?
• Core developer @ Unity
• Released games
• LIMBO
• Watchmen
• Total overdose
• Unity focus areas
• CPU performance
• Memory optimizations
09-05-2013 2
Page
Optimizing your game
• FPS
• CPU usage
(Gamecode, Physics, Skinning, Particles, …)
• GPU usage (Drawcalls, Shader usage, Image
effects, …)
• Hickups
• Spikes in framerate caused by heavy tasks (e.g.
GC.Collect)
• Physics world rebuild due to moved static colliders
• Memory
• Maintaining small runtime memory on device
• Avoid GC Hickups by reducing memory activity
• Leak detection
09-05-2013 3
Page
Performance
• Unity Profiler (Pro Feature)
• CPU
• GPU
• Memory usage
• New Detailed memory view (Unity 4.1)
• Memory reference view (Unity 4.2)
09-05-2013 4
Page
CPU Profiler
• Cpu time consumption for methods
• Mono memory activity
• Remote Profiling of you game running on target device
• Deep profile (editor only)
• Detailed view, but large overhead, only usable for very small
scenes
09-05-2013 5
Page
Memory Profiler
• Simple and Detailed memory view (Unity 4.1)
• Detail view is taken as a snapshot (too expensive for per
frame)
• Reference view (Unity 4.2)
• See where an object is referenced – Good for leak hunting
09-05-2013 7
Page
Memory Profiler
09-05-2013 8
• Simple memory view
• Unity reserves chunks of memory from the os
• Mono allocates from a reserved heap
• GfxMemory is an estimate
Page
Mono vs. Unity Memory
• Managed - Mono
• Script objects
• Wrappers for unity
objects
• Game objects
• Assets
• Components
• …
• Memory is garbage
collected
09-05-2013 9
• Native - Unity internal
• Asset data
• Textures
• Meshes
• Audio
• Animation
• Game objects
• Engine internals
• Rendering
• Particles
• Webstreams
• Physics
• …..
Page
Mono Memory Internals
• Allocates system heap blocks for allocations
• Garbage collector cleans up
• Will allocate new heap blocks when needed
• Fragmentation can cause new heap blocks even
though memory is not exhausted
• Heap blocks are kept in Mono for later use
• Memory can be given back to the system after a while
09-05-2013 10
Page
Fragmentation
• Memory will get fragmentet if there is a lot of
activity
09-05-2013 11
Mono: 16K System:
64K
Mono: 32K System:
64K
Mono: 32K System:
64K
Mono: 48K System:
128K
Page
Avoiding Allocations
• Reuse temporary buffers
• If buffers for data processing are needed every
frame, allocate the buffer once and reuse
• Allocate pools of reusable objects
• Create freelists for objects that are needed often
• Use structs instead of classes
• Structs are placed on the stack, while classes uses the
heap
• Don’t use OnGUI
• Even empty OnGUI calls are very memory intensive
09-05-2013 12
Page
Avoiding Allocations
• Use the CPU profiler to identify mono allocations
09-05-2013 13
Page
Unity Object wrapper
• Some Objects used in scripts have large native
backing memory in unity
• Memory not freed until Finalizers have run
09-05-2013 14
WWW
Decompression buffer
Compressed file
Decompressed file
Managed Native
Page
Mono Garbage Collection
• Object goes out of scope
• GC.Collect runs when
• Mono exhausts the heap space
• Or user calls System.GC.Collect()
• Finalizers
• Run on a separate thread
• Unity native memory
• Dispose() cleans up internal
memory
• Eventually called from finalizer
• Manually call Dispose() to cleanup
09-05-2013 15
Main thread Finalizer thread
www = null;
new(someclass
);
//no more heap
-> GC.Collect();
www.Dispose();
.....
Page
Garbage collect and Dispose
Demo
09-05-2013 16
Page
Assetbundle memory usage
• WebStream
• Compressed file
• Decompression buffers
• Uncompressed file
• Assetbundle
• Map of objects and offsets in WebStream
• Instantiated objects
• Textures, Meshes, etc.
09-05-2013 17
Page
Assetbundle memory usage
• WWW www = new WWW(assetbundle_url);
• Loads the compressed file into memory
• Constructs decompression buffers (8MB per file)
• Decompresses the file into memory
• Deallocates the decompression buffers
• One decompression buffer of 8MB is reused and
never deallocated
09-05-2013 18
Page
Assetbundle memory usage
• AssetBundle ab = www.assetBundle;
• Loads the map of where objects are in the webstream
• Retains the www WebStream
09-05-2013 19
WebStream
Tex
Tex
Mes
h
AssetBundle
Page
Assetbundle memory usage
• AssetBundle ab = www.assetBundle;
• Loads the map of where objects are in the webstream
• Retains the www WebStream
09-05-2013 20
WebStream
Tex
Tex
Mes
h
AssetBundle
Loaded objects
Page
Assetbundle memory usage
• Texture2D tex =
ab.Load(“MyTex", typeof(Texture2D));
• Instantiates a texture from the assetbundle
• Uploads the texture to the GPU
• On editor a system copy is retained (2x memory)
• Transferbuffer for the RenderThread will grow to fit the
largest Texture or Vertexbuffer (never shrinks)
09-05-2013 21
Page
Assetbundle memory usage
• Deleting the WebStream
• www.Dispose(); // will count down the retain count
• If not called, finalizers will clean the memory eventually
• Deleting the Assetbundle
• ab.Unload(false);
• Unloads the map and counts down the www retain count
• ab.Unload(true);
• Will also force unload all assets created from the
assetbundle
09-05-2013 22
Page
Assetbundle memory usage
• Removing the loaded objects from memory
• ab.Unload(true)
• Force unload objects loaded by assetbundle
• UnloadUnusedAssets()
• Unloads when there are no more references to the object
• Use the memory profiler to find remaining
references
• In Unity 4.1 a reason why a Object is given
• In Unity 4.2 specific scripts or Objects referencing a
given object are shown
09-05-2013 23
Page
Assetbundle memory usage
• For best memory efficiency do one assetbundle at
a time
• If more assetbundles are needed at the same
time, load one www object into memory at a time, to
reduce decompression buffer usage
09-05-2013 24
Page
Assetbundle memory usage
Demo
09-05-2013 25
Page
Conclusions
• Avoid memory activity
• Use the memory profiler to monitor memory usage
• Load one WWW object at a time
• Use Dispose() on objects that derive from IDisposable
• Specially if they have a large native memory footprint
• Use UnloadUnusedAssets() to clean up assets
09-05-2013 26
Page
Questions?
09-05-2013 27

More Related Content

What's hot

Unity - Internals: memory and performance
Unity - Internals: memory and performanceUnity - Internals: memory and performance
Unity - Internals: memory and performanceCodemotion
 
Terrain Rendering using GPU-Based Geometry Clipmaps
Terrain Rendering usingGPU-Based Geometry ClipmapsTerrain Rendering usingGPU-Based Geometry Clipmaps
Terrain Rendering using GPU-Based Geometry Clipmapsnone299359
 
Z Buffer Optimizations
Z Buffer OptimizationsZ Buffer Optimizations
Z Buffer Optimizationspjcozzi
 
Decima Engine: Visibility in Horizon Zero Dawn
Decima Engine: Visibility in Horizon Zero DawnDecima Engine: Visibility in Horizon Zero Dawn
Decima Engine: Visibility in Horizon Zero DawnGuerrilla
 
Masked Software Occlusion Culling
Masked Software Occlusion CullingMasked Software Occlusion Culling
Masked Software Occlusion CullingIntel® Software
 
Advanced Scenegraph Rendering Pipeline
Advanced Scenegraph Rendering PipelineAdvanced Scenegraph Rendering Pipeline
Advanced Scenegraph Rendering PipelineNarann29
 
OpenGL 4.4 - Scene Rendering Techniques
OpenGL 4.4 - Scene Rendering TechniquesOpenGL 4.4 - Scene Rendering Techniques
OpenGL 4.4 - Scene Rendering TechniquesNarann29
 
Parallel Futures of a Game Engine
Parallel Futures of a Game EngineParallel Futures of a Game Engine
Parallel Futures of a Game EngineJohan Andersson
 
서버와 클라이언트 같은 엔진 사용하기
서버와 클라이언트 같은 엔진 사용하기서버와 클라이언트 같은 엔진 사용하기
서버와 클라이언트 같은 엔진 사용하기YEONG-CHEON YOU
 
Intrinsics: Low-level engine development with Burst - Unite Copenhagen 2019
Intrinsics: Low-level engine development with Burst - Unite Copenhagen 2019 Intrinsics: Low-level engine development with Burst - Unite Copenhagen 2019
Intrinsics: Low-level engine development with Burst - Unite Copenhagen 2019 Unity Technologies
 
Scene Graphs & Component Based Game Engines
Scene Graphs & Component Based Game EnginesScene Graphs & Component Based Game Engines
Scene Graphs & Component Based Game EnginesBryan Duggan
 
Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016Graham Wihlidal
 
Recast Detour.pptx
Recast Detour.pptxRecast Detour.pptx
Recast Detour.pptxMUUMUMUMU
 
Best practices: Async vs. coroutines - Unite Copenhagen 2019
Best practices: Async vs. coroutines - Unite Copenhagen 2019Best practices: Async vs. coroutines - Unite Copenhagen 2019
Best practices: Async vs. coroutines - Unite Copenhagen 2019Unity Technologies
 
OpenGL 3.2 and More
OpenGL 3.2 and MoreOpenGL 3.2 and More
OpenGL 3.2 and MoreMark Kilgard
 
Precomputed Voxelized-Shadows for Large-scale Scene and Many lights
Precomputed Voxelized-Shadows for Large-scale Scene and Many lightsPrecomputed Voxelized-Shadows for Large-scale Scene and Many lights
Precomputed Voxelized-Shadows for Large-scale Scene and Many lightsSeongdae Kim
 
FrameGraph: Extensible Rendering Architecture in Frostbite
FrameGraph: Extensible Rendering Architecture in FrostbiteFrameGraph: Extensible Rendering Architecture in Frostbite
FrameGraph: Extensible Rendering Architecture in FrostbiteElectronic Arts / DICE
 
Secrets of CryENGINE 3 Graphics Technology
Secrets of CryENGINE 3 Graphics TechnologySecrets of CryENGINE 3 Graphics Technology
Secrets of CryENGINE 3 Graphics TechnologyTiago Sousa
 

What's hot (20)

Unity - Internals: memory and performance
Unity - Internals: memory and performanceUnity - Internals: memory and performance
Unity - Internals: memory and performance
 
Gstreamer plugin development
Gstreamer plugin development Gstreamer plugin development
Gstreamer plugin development
 
Terrain Rendering using GPU-Based Geometry Clipmaps
Terrain Rendering usingGPU-Based Geometry ClipmapsTerrain Rendering usingGPU-Based Geometry Clipmaps
Terrain Rendering using GPU-Based Geometry Clipmaps
 
Z Buffer Optimizations
Z Buffer OptimizationsZ Buffer Optimizations
Z Buffer Optimizations
 
Decima Engine: Visibility in Horizon Zero Dawn
Decima Engine: Visibility in Horizon Zero DawnDecima Engine: Visibility in Horizon Zero Dawn
Decima Engine: Visibility in Horizon Zero Dawn
 
Masked Software Occlusion Culling
Masked Software Occlusion CullingMasked Software Occlusion Culling
Masked Software Occlusion Culling
 
Advanced Scenegraph Rendering Pipeline
Advanced Scenegraph Rendering PipelineAdvanced Scenegraph Rendering Pipeline
Advanced Scenegraph Rendering Pipeline
 
OpenGL 4.4 - Scene Rendering Techniques
OpenGL 4.4 - Scene Rendering TechniquesOpenGL 4.4 - Scene Rendering Techniques
OpenGL 4.4 - Scene Rendering Techniques
 
Parallel Futures of a Game Engine
Parallel Futures of a Game EngineParallel Futures of a Game Engine
Parallel Futures of a Game Engine
 
서버와 클라이언트 같은 엔진 사용하기
서버와 클라이언트 같은 엔진 사용하기서버와 클라이언트 같은 엔진 사용하기
서버와 클라이언트 같은 엔진 사용하기
 
Lighting you up in Battlefield 3
Lighting you up in Battlefield 3Lighting you up in Battlefield 3
Lighting you up in Battlefield 3
 
Intrinsics: Low-level engine development with Burst - Unite Copenhagen 2019
Intrinsics: Low-level engine development with Burst - Unite Copenhagen 2019 Intrinsics: Low-level engine development with Burst - Unite Copenhagen 2019
Intrinsics: Low-level engine development with Burst - Unite Copenhagen 2019
 
Scene Graphs & Component Based Game Engines
Scene Graphs & Component Based Game EnginesScene Graphs & Component Based Game Engines
Scene Graphs & Component Based Game Engines
 
Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016
 
Recast Detour.pptx
Recast Detour.pptxRecast Detour.pptx
Recast Detour.pptx
 
Best practices: Async vs. coroutines - Unite Copenhagen 2019
Best practices: Async vs. coroutines - Unite Copenhagen 2019Best practices: Async vs. coroutines - Unite Copenhagen 2019
Best practices: Async vs. coroutines - Unite Copenhagen 2019
 
OpenGL 3.2 and More
OpenGL 3.2 and MoreOpenGL 3.2 and More
OpenGL 3.2 and More
 
Precomputed Voxelized-Shadows for Large-scale Scene and Many lights
Precomputed Voxelized-Shadows for Large-scale Scene and Many lightsPrecomputed Voxelized-Shadows for Large-scale Scene and Many lights
Precomputed Voxelized-Shadows for Large-scale Scene and Many lights
 
FrameGraph: Extensible Rendering Architecture in Frostbite
FrameGraph: Extensible Rendering Architecture in FrostbiteFrameGraph: Extensible Rendering Architecture in Frostbite
FrameGraph: Extensible Rendering Architecture in Frostbite
 
Secrets of CryENGINE 3 Graphics Technology
Secrets of CryENGINE 3 Graphics TechnologySecrets of CryENGINE 3 Graphics Technology
Secrets of CryENGINE 3 Graphics Technology
 

Viewers also liked

ラクガキ忍者制作秘話
ラクガキ忍者制作秘話ラクガキ忍者制作秘話
ラクガキ忍者制作秘話koppepan
 
「会社で寝よう!」制作レポート(3Dカジュアルゲームの開発手法)
「会社で寝よう!」制作レポート(3Dカジュアルゲームの開発手法)「会社で寝よう!」制作レポート(3Dカジュアルゲームの開発手法)
「会社で寝よう!」制作レポート(3Dカジュアルゲームの開発手法)ミルク株式会社
 
Unityプロファイラについて
UnityプロファイラについてUnityプロファイラについて
UnityプロファイラについてMio Ku-tani
 
SIG-Audio#6 プラグインを書かなくてもここまで出来る!Unityサウンド
SIG-Audio#6 プラグインを書かなくてもここまで出来る!UnityサウンドSIG-Audio#6 プラグインを書かなくてもここまで出来る!Unityサウンド
SIG-Audio#6 プラグインを書かなくてもここまで出来る!UnityサウンドIGDA Japan SIG-Audio
 
「もののけ大戦“陣”」製作事例
「もののけ大戦“陣”」製作事例「もののけ大戦“陣”」製作事例
「もののけ大戦“陣”」製作事例Ryohei Tokimura
 
Minko - Creating cross-platform 3D apps with Minko
Minko - Creating cross-platform 3D apps with MinkoMinko - Creating cross-platform 3D apps with Minko
Minko - Creating cross-platform 3D apps with MinkoMinko3D
 
Mathieu Muller, Field Engineer Unity Technologies - Unity 5: Easier, Better, ...
Mathieu Muller, Field Engineer Unity Technologies - Unity 5: Easier, Better, ...Mathieu Muller, Field Engineer Unity Technologies - Unity 5: Easier, Better, ...
Mathieu Muller, Field Engineer Unity Technologies - Unity 5: Easier, Better, ...How to Web
 
Make "PONG" : 아키텍팅과 동기화 테크닉
Make "PONG" : 아키텍팅과 동기화 테크닉Make "PONG" : 아키텍팅과 동기화 테크닉
Make "PONG" : 아키텍팅과 동기화 테크닉iFunFactory Inc.
 
2016 NDC - 클라우드 시대의 모바일 게임 운영 플랫폼 구현
2016 NDC  - 클라우드 시대의  모바일 게임 운영 플랫폼 구현2016 NDC  - 클라우드 시대의  모바일 게임 운영 플랫폼 구현
2016 NDC - 클라우드 시대의 모바일 게임 운영 플랫폼 구현iFunFactory Inc.
 
게임 운영에 필요한 로그성 데이터들에 대하여
게임 운영에 필요한 로그성 데이터들에 대하여게임 운영에 필요한 로그성 데이터들에 대하여
게임 운영에 필요한 로그성 데이터들에 대하여iFunFactory Inc.
 
Unity technologies on BarCamp Vilnius
Unity technologies on BarCamp VilniusUnity technologies on BarCamp Vilnius
Unity technologies on BarCamp VilniusBarCamp Lithuania
 
ダイスふる制作レポート Unityでアプリ個人開発
ダイスふる制作レポート Unityでアプリ個人開発ダイスふる制作レポート Unityでアプリ個人開発
ダイスふる制作レポート Unityでアプリ個人開発Ryohei Tokimura
 
Asset bundleなどの、Unity3d基礎知識
Asset bundleなどの、Unity3d基礎知識Asset bundleなどの、Unity3d基礎知識
Asset bundleなどの、Unity3d基礎知識Nobukazu Hanada
 
Practical guide to optimization in Unity
Practical guide to optimization in UnityPractical guide to optimization in Unity
Practical guide to optimization in UnityDevGAMM Conference
 
Unity名古屋セミナー [Shadowgun]
Unity名古屋セミナー [Shadowgun]Unity名古屋セミナー [Shadowgun]
Unity名古屋セミナー [Shadowgun]MakotoItoh
 
[IGC 2016] 유니티코리아 오지현 - “뭣이 중헌디? 성능 프로파일링도 모름서”: 유니티 성능 프로파일링 가이드
[IGC 2016] 유니티코리아 오지현 - “뭣이 중헌디? 성능 프로파일링도 모름서”: 유니티 성능 프로파일링 가이드[IGC 2016] 유니티코리아 오지현 - “뭣이 중헌디? 성능 프로파일링도 모름서”: 유니티 성능 프로파일링 가이드
[IGC 2016] 유니티코리아 오지현 - “뭣이 중헌디? 성능 프로파일링도 모름서”: 유니티 성능 프로파일링 가이드강 민우
 
GREE流 新次元ゲーム開発
GREE流 新次元ゲーム開発GREE流 新次元ゲーム開発
GREE流 新次元ゲーム開発Kazuki Sakamoto
 
PC 와 모바일에서의 P2P 게임 구현에서의 차이점 비교
PC 와 모바일에서의 P2P 게임 구현에서의 차이점 비교PC 와 모바일에서의 P2P 게임 구현에서의 차이점 비교
PC 와 모바일에서의 P2P 게임 구현에서의 차이점 비교iFunFactory Inc.
 
Practical Guide for Optimizing Unity on Mobiles
Practical Guide for Optimizing Unity on MobilesPractical Guide for Optimizing Unity on Mobiles
Practical Guide for Optimizing Unity on MobilesValentin Simonov
 
2016 NDC - 모바일 게임 서버 엔진 개발 후기
2016 NDC - 모바일 게임 서버 엔진 개발 후기2016 NDC - 모바일 게임 서버 엔진 개발 후기
2016 NDC - 모바일 게임 서버 엔진 개발 후기iFunFactory Inc.
 

Viewers also liked (20)

ラクガキ忍者制作秘話
ラクガキ忍者制作秘話ラクガキ忍者制作秘話
ラクガキ忍者制作秘話
 
「会社で寝よう!」制作レポート(3Dカジュアルゲームの開発手法)
「会社で寝よう!」制作レポート(3Dカジュアルゲームの開発手法)「会社で寝よう!」制作レポート(3Dカジュアルゲームの開発手法)
「会社で寝よう!」制作レポート(3Dカジュアルゲームの開発手法)
 
Unityプロファイラについて
UnityプロファイラについてUnityプロファイラについて
Unityプロファイラについて
 
SIG-Audio#6 プラグインを書かなくてもここまで出来る!Unityサウンド
SIG-Audio#6 プラグインを書かなくてもここまで出来る!UnityサウンドSIG-Audio#6 プラグインを書かなくてもここまで出来る!Unityサウンド
SIG-Audio#6 プラグインを書かなくてもここまで出来る!Unityサウンド
 
「もののけ大戦“陣”」製作事例
「もののけ大戦“陣”」製作事例「もののけ大戦“陣”」製作事例
「もののけ大戦“陣”」製作事例
 
Minko - Creating cross-platform 3D apps with Minko
Minko - Creating cross-platform 3D apps with MinkoMinko - Creating cross-platform 3D apps with Minko
Minko - Creating cross-platform 3D apps with Minko
 
Mathieu Muller, Field Engineer Unity Technologies - Unity 5: Easier, Better, ...
Mathieu Muller, Field Engineer Unity Technologies - Unity 5: Easier, Better, ...Mathieu Muller, Field Engineer Unity Technologies - Unity 5: Easier, Better, ...
Mathieu Muller, Field Engineer Unity Technologies - Unity 5: Easier, Better, ...
 
Make "PONG" : 아키텍팅과 동기화 테크닉
Make "PONG" : 아키텍팅과 동기화 테크닉Make "PONG" : 아키텍팅과 동기화 테크닉
Make "PONG" : 아키텍팅과 동기화 테크닉
 
2016 NDC - 클라우드 시대의 모바일 게임 운영 플랫폼 구현
2016 NDC  - 클라우드 시대의  모바일 게임 운영 플랫폼 구현2016 NDC  - 클라우드 시대의  모바일 게임 운영 플랫폼 구현
2016 NDC - 클라우드 시대의 모바일 게임 운영 플랫폼 구현
 
게임 운영에 필요한 로그성 데이터들에 대하여
게임 운영에 필요한 로그성 데이터들에 대하여게임 운영에 필요한 로그성 데이터들에 대하여
게임 운영에 필요한 로그성 데이터들에 대하여
 
Unity technologies on BarCamp Vilnius
Unity technologies on BarCamp VilniusUnity technologies on BarCamp Vilnius
Unity technologies on BarCamp Vilnius
 
ダイスふる制作レポート Unityでアプリ個人開発
ダイスふる制作レポート Unityでアプリ個人開発ダイスふる制作レポート Unityでアプリ個人開発
ダイスふる制作レポート Unityでアプリ個人開発
 
Asset bundleなどの、Unity3d基礎知識
Asset bundleなどの、Unity3d基礎知識Asset bundleなどの、Unity3d基礎知識
Asset bundleなどの、Unity3d基礎知識
 
Practical guide to optimization in Unity
Practical guide to optimization in UnityPractical guide to optimization in Unity
Practical guide to optimization in Unity
 
Unity名古屋セミナー [Shadowgun]
Unity名古屋セミナー [Shadowgun]Unity名古屋セミナー [Shadowgun]
Unity名古屋セミナー [Shadowgun]
 
[IGC 2016] 유니티코리아 오지현 - “뭣이 중헌디? 성능 프로파일링도 모름서”: 유니티 성능 프로파일링 가이드
[IGC 2016] 유니티코리아 오지현 - “뭣이 중헌디? 성능 프로파일링도 모름서”: 유니티 성능 프로파일링 가이드[IGC 2016] 유니티코리아 오지현 - “뭣이 중헌디? 성능 프로파일링도 모름서”: 유니티 성능 프로파일링 가이드
[IGC 2016] 유니티코리아 오지현 - “뭣이 중헌디? 성능 프로파일링도 모름서”: 유니티 성능 프로파일링 가이드
 
GREE流 新次元ゲーム開発
GREE流 新次元ゲーム開発GREE流 新次元ゲーム開発
GREE流 新次元ゲーム開発
 
PC 와 모바일에서의 P2P 게임 구현에서의 차이점 비교
PC 와 모바일에서의 P2P 게임 구현에서의 차이점 비교PC 와 모바일에서의 P2P 게임 구현에서의 차이점 비교
PC 와 모바일에서의 P2P 게임 구현에서의 차이점 비교
 
Practical Guide for Optimizing Unity on Mobiles
Practical Guide for Optimizing Unity on MobilesPractical Guide for Optimizing Unity on Mobiles
Practical Guide for Optimizing Unity on Mobiles
 
2016 NDC - 모바일 게임 서버 엔진 개발 후기
2016 NDC - 모바일 게임 서버 엔진 개발 후기2016 NDC - 모바일 게임 서버 엔진 개발 후기
2016 NDC - 모바일 게임 서버 엔진 개발 후기
 

Similar to [UniteKorea2013] Memory profiling in Unity

Things I wish I knew about GemStone
Things I wish I knew about GemStoneThings I wish I knew about GemStone
Things I wish I knew about GemStoneESUG
 
【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~
【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~
【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~Unity Technologies Japan K.K.
 
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法Unite2017Tokyo
 
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法Unity Technologies Japan K.K.
 
XPDS13: Zero-copy display of guest framebuffers using GEM - John Baboval, Citrix
XPDS13: Zero-copy display of guest framebuffers using GEM - John Baboval, CitrixXPDS13: Zero-copy display of guest framebuffers using GEM - John Baboval, Citrix
XPDS13: Zero-copy display of guest framebuffers using GEM - John Baboval, CitrixThe Linux Foundation
 
Deployment Strategies (Mongo Austin)
Deployment Strategies (Mongo Austin)Deployment Strategies (Mongo Austin)
Deployment Strategies (Mongo Austin)MongoDB
 
Ruby and Distributed Storage Systems
Ruby and Distributed Storage SystemsRuby and Distributed Storage Systems
Ruby and Distributed Storage SystemsSATOSHI TAGOMORI
 
EuroSec2012 "Effects of Memory Randomization, Sanitization and Page Cache on ...
EuroSec2012 "Effects of Memory Randomization, Sanitization and Page Cache on ...EuroSec2012 "Effects of Memory Randomization, Sanitization and Page Cache on ...
EuroSec2012 "Effects of Memory Randomization, Sanitization and Page Cache on ...Kuniyasu Suzaki
 
Data Management and Streaming Strategies in Drakensang Online
Data Management and Streaming Strategies in Drakensang OnlineData Management and Streaming Strategies in Drakensang Online
Data Management and Streaming Strategies in Drakensang OnlineAndre Weissflog
 
Chronicles Of Garbage Collection (GC)
Chronicles Of Garbage Collection (GC)Chronicles Of Garbage Collection (GC)
Chronicles Of Garbage Collection (GC)Techizzaa
 
Memory management in Andoid
Memory management in AndoidMemory management in Andoid
Memory management in AndoidMonkop Inc
 
Deployment Strategy
Deployment StrategyDeployment Strategy
Deployment StrategyMongoDB
 
Driver development – memory management
Driver development – memory managementDriver development – memory management
Driver development – memory managementVandana Salve
 
Linux kernel memory allocators
Linux kernel memory allocatorsLinux kernel memory allocators
Linux kernel memory allocatorsHao-Ran Liu
 
NDH2k12 Cloud Computing Security
NDH2k12 Cloud Computing SecurityNDH2k12 Cloud Computing Security
NDH2k12 Cloud Computing SecurityMatthieu Bouthors
 
Improving Game Performance in the Browser
Improving Game Performance in the BrowserImproving Game Performance in the Browser
Improving Game Performance in the BrowserFITC
 
Deployment Strategies
Deployment StrategiesDeployment Strategies
Deployment StrategiesMongoDB
 
When Smalltalk images get large
When Smalltalk images get largeWhen Smalltalk images get large
When Smalltalk images get largeESUG
 

Similar to [UniteKorea2013] Memory profiling in Unity (20)

Things I wish I knew about GemStone
Things I wish I knew about GemStoneThings I wish I knew about GemStone
Things I wish I knew about GemStone
 
【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~
【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~
【Unite Tokyo 2018】その最適化、本当に最適ですか!? ~正しい最適化を行うためのテクニック~
 
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
 
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
 
XPDS13: Zero-copy display of guest framebuffers using GEM - John Baboval, Citrix
XPDS13: Zero-copy display of guest framebuffers using GEM - John Baboval, CitrixXPDS13: Zero-copy display of guest framebuffers using GEM - John Baboval, Citrix
XPDS13: Zero-copy display of guest framebuffers using GEM - John Baboval, Citrix
 
Deployment Strategies (Mongo Austin)
Deployment Strategies (Mongo Austin)Deployment Strategies (Mongo Austin)
Deployment Strategies (Mongo Austin)
 
Ruby and Distributed Storage Systems
Ruby and Distributed Storage SystemsRuby and Distributed Storage Systems
Ruby and Distributed Storage Systems
 
EuroSec2012 "Effects of Memory Randomization, Sanitization and Page Cache on ...
EuroSec2012 "Effects of Memory Randomization, Sanitization and Page Cache on ...EuroSec2012 "Effects of Memory Randomization, Sanitization and Page Cache on ...
EuroSec2012 "Effects of Memory Randomization, Sanitization and Page Cache on ...
 
Data Management and Streaming Strategies in Drakensang Online
Data Management and Streaming Strategies in Drakensang OnlineData Management and Streaming Strategies in Drakensang Online
Data Management and Streaming Strategies in Drakensang Online
 
Chronicles Of Garbage Collection (GC)
Chronicles Of Garbage Collection (GC)Chronicles Of Garbage Collection (GC)
Chronicles Of Garbage Collection (GC)
 
Memory management in Andoid
Memory management in AndoidMemory management in Andoid
Memory management in Andoid
 
memory_mapping.ppt
memory_mapping.pptmemory_mapping.ppt
memory_mapping.ppt
 
week1slides1704202828322.pdf
week1slides1704202828322.pdfweek1slides1704202828322.pdf
week1slides1704202828322.pdf
 
Deployment Strategy
Deployment StrategyDeployment Strategy
Deployment Strategy
 
Driver development – memory management
Driver development – memory managementDriver development – memory management
Driver development – memory management
 
Linux kernel memory allocators
Linux kernel memory allocatorsLinux kernel memory allocators
Linux kernel memory allocators
 
NDH2k12 Cloud Computing Security
NDH2k12 Cloud Computing SecurityNDH2k12 Cloud Computing Security
NDH2k12 Cloud Computing Security
 
Improving Game Performance in the Browser
Improving Game Performance in the BrowserImproving Game Performance in the Browser
Improving Game Performance in the Browser
 
Deployment Strategies
Deployment StrategiesDeployment Strategies
Deployment Strategies
 
When Smalltalk images get large
When Smalltalk images get largeWhen Smalltalk images get large
When Smalltalk images get large
 

More from William Hugo Yang

[UniteKorea2013] Protecting your Android content
[UniteKorea2013] Protecting your Android content[UniteKorea2013] Protecting your Android content
[UniteKorea2013] Protecting your Android contentWilliam Hugo Yang
 
[UniteKorea2013] Serialization in Depth
[UniteKorea2013] Serialization in Depth[UniteKorea2013] Serialization in Depth
[UniteKorea2013] Serialization in DepthWilliam Hugo Yang
 
[UniteKorea2013] Unity Hacks
[UniteKorea2013] Unity Hacks[UniteKorea2013] Unity Hacks
[UniteKorea2013] Unity HacksWilliam Hugo Yang
 
[UniteKorea2013] Butterfly Effect DX11
[UniteKorea2013] Butterfly Effect DX11[UniteKorea2013] Butterfly Effect DX11
[UniteKorea2013] Butterfly Effect DX11William Hugo Yang
 
[UniteKorea2013] The Unity Rendering Pipeline
[UniteKorea2013] The Unity Rendering Pipeline[UniteKorea2013] The Unity Rendering Pipeline
[UniteKorea2013] The Unity Rendering PipelineWilliam Hugo Yang
 
[UniteKorea2013] Art tips and tricks
[UniteKorea2013] Art tips and tricks[UniteKorea2013] Art tips and tricks
[UniteKorea2013] Art tips and tricksWilliam Hugo Yang
 
[UniteKorea2013] 2D content workflows
[UniteKorea2013] 2D content workflows[UniteKorea2013] 2D content workflows
[UniteKorea2013] 2D content workflowsWilliam Hugo Yang
 

More from William Hugo Yang (7)

[UniteKorea2013] Protecting your Android content
[UniteKorea2013] Protecting your Android content[UniteKorea2013] Protecting your Android content
[UniteKorea2013] Protecting your Android content
 
[UniteKorea2013] Serialization in Depth
[UniteKorea2013] Serialization in Depth[UniteKorea2013] Serialization in Depth
[UniteKorea2013] Serialization in Depth
 
[UniteKorea2013] Unity Hacks
[UniteKorea2013] Unity Hacks[UniteKorea2013] Unity Hacks
[UniteKorea2013] Unity Hacks
 
[UniteKorea2013] Butterfly Effect DX11
[UniteKorea2013] Butterfly Effect DX11[UniteKorea2013] Butterfly Effect DX11
[UniteKorea2013] Butterfly Effect DX11
 
[UniteKorea2013] The Unity Rendering Pipeline
[UniteKorea2013] The Unity Rendering Pipeline[UniteKorea2013] The Unity Rendering Pipeline
[UniteKorea2013] The Unity Rendering Pipeline
 
[UniteKorea2013] Art tips and tricks
[UniteKorea2013] Art tips and tricks[UniteKorea2013] Art tips and tricks
[UniteKorea2013] Art tips and tricks
 
[UniteKorea2013] 2D content workflows
[UniteKorea2013] 2D content workflows[UniteKorea2013] 2D content workflows
[UniteKorea2013] 2D content workflows
 

Recently uploaded

The-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdf
The-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdfThe-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdf
The-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdfSana Khan
 
empathy map for students very useful.pptx
empathy map for students very useful.pptxempathy map for students very useful.pptx
empathy map for students very useful.pptxGeorgePhilips7
 
Codex Singularity: Search for the Prisca Sapientia
Codex Singularity: Search for the Prisca SapientiaCodex Singularity: Search for the Prisca Sapientia
Codex Singularity: Search for the Prisca Sapientiajfrenchau
 
The King 'Great Goodness' Part 1 Mahasilava Jataka (Eng. & Chi.).pptx
The King 'Great Goodness' Part 1 Mahasilava Jataka (Eng. & Chi.).pptxThe King 'Great Goodness' Part 1 Mahasilava Jataka (Eng. & Chi.).pptx
The King 'Great Goodness' Part 1 Mahasilava Jataka (Eng. & Chi.).pptxOH TEIK BIN
 
A Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptx
A Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptxA Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptx
A Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptxOH TEIK BIN
 
Prach Autism AI - Artificial Intelligence
Prach Autism AI - Artificial IntelligencePrach Autism AI - Artificial Intelligence
Prach Autism AI - Artificial Intelligenceprachaibot
 
Deerfoot Church of Christ Bulletin 2 25 24
Deerfoot Church of Christ Bulletin 2 25 24Deerfoot Church of Christ Bulletin 2 25 24
Deerfoot Church of Christ Bulletin 2 25 24deerfootcoc
 
PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!spy7777777guy
 
Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...
Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...
Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...INDIAN YOUTH SECURED ORGANISATION
 
Deerfoot Church of Christ Bulletin 4 14 24
Deerfoot Church of Christ Bulletin 4 14 24Deerfoot Church of Christ Bulletin 4 14 24
Deerfoot Church of Christ Bulletin 4 14 24deerfootcoc
 
Meaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptx
Meaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptxMeaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptx
Meaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptxStephen Palm
 
A357 Hate can stir up strife, but love can cover up all mistakes. hate, love...
A357 Hate can stir up strife, but love can cover up all mistakes.  hate, love...A357 Hate can stir up strife, but love can cover up all mistakes.  hate, love...
A357 Hate can stir up strife, but love can cover up all mistakes. hate, love...franktsao4
 
"There are probably more Nobel Laureates who are people of faith than is gen...
 "There are probably more Nobel Laureates who are people of faith than is gen... "There are probably more Nobel Laureates who are people of faith than is gen...
"There are probably more Nobel Laureates who are people of faith than is gen...Steven Camilleri
 
PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!spy7777777guy
 
Deerfoot Church of Christ Bulletin 3 31 24
Deerfoot Church of Christ Bulletin 3 31 24Deerfoot Church of Christ Bulletin 3 31 24
Deerfoot Church of Christ Bulletin 3 31 24deerfootcoc
 
A MEMORIAL TRIBUTE TO THE FOUR BROTHER BILLS
A MEMORIAL TRIBUTE TO THE FOUR BROTHER BILLSA MEMORIAL TRIBUTE TO THE FOUR BROTHER BILLS
A MEMORIAL TRIBUTE TO THE FOUR BROTHER BILLSRickPatrick9
 

Recently uploaded (19)

The-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdf
The-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdfThe-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdf
The-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdf
 
empathy map for students very useful.pptx
empathy map for students very useful.pptxempathy map for students very useful.pptx
empathy map for students very useful.pptx
 
Codex Singularity: Search for the Prisca Sapientia
Codex Singularity: Search for the Prisca SapientiaCodex Singularity: Search for the Prisca Sapientia
Codex Singularity: Search for the Prisca Sapientia
 
The King 'Great Goodness' Part 1 Mahasilava Jataka (Eng. & Chi.).pptx
The King 'Great Goodness' Part 1 Mahasilava Jataka (Eng. & Chi.).pptxThe King 'Great Goodness' Part 1 Mahasilava Jataka (Eng. & Chi.).pptx
The King 'Great Goodness' Part 1 Mahasilava Jataka (Eng. & Chi.).pptx
 
A Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptx
A Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptxA Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptx
A Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptx
 
Prach Autism AI - Artificial Intelligence
Prach Autism AI - Artificial IntelligencePrach Autism AI - Artificial Intelligence
Prach Autism AI - Artificial Intelligence
 
Deerfoot Church of Christ Bulletin 2 25 24
Deerfoot Church of Christ Bulletin 2 25 24Deerfoot Church of Christ Bulletin 2 25 24
Deerfoot Church of Christ Bulletin 2 25 24
 
PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!
 
Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...
Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...
Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...
 
The Precious Blood of the Lord Jesus Christ.pptx
The Precious Blood of the Lord Jesus Christ.pptxThe Precious Blood of the Lord Jesus Christ.pptx
The Precious Blood of the Lord Jesus Christ.pptx
 
Deerfoot Church of Christ Bulletin 4 14 24
Deerfoot Church of Christ Bulletin 4 14 24Deerfoot Church of Christ Bulletin 4 14 24
Deerfoot Church of Christ Bulletin 4 14 24
 
The spiritual moderator of vincentian groups
The spiritual moderator of vincentian groupsThe spiritual moderator of vincentian groups
The spiritual moderator of vincentian groups
 
Meaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptx
Meaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptxMeaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptx
Meaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptx
 
A357 Hate can stir up strife, but love can cover up all mistakes. hate, love...
A357 Hate can stir up strife, but love can cover up all mistakes.  hate, love...A357 Hate can stir up strife, but love can cover up all mistakes.  hate, love...
A357 Hate can stir up strife, but love can cover up all mistakes. hate, love...
 
"There are probably more Nobel Laureates who are people of faith than is gen...
 "There are probably more Nobel Laureates who are people of faith than is gen... "There are probably more Nobel Laureates who are people of faith than is gen...
"There are probably more Nobel Laureates who are people of faith than is gen...
 
English - The Dangers of Wine Alcohol.pptx
English - The Dangers of Wine Alcohol.pptxEnglish - The Dangers of Wine Alcohol.pptx
English - The Dangers of Wine Alcohol.pptx
 
PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!
 
Deerfoot Church of Christ Bulletin 3 31 24
Deerfoot Church of Christ Bulletin 3 31 24Deerfoot Church of Christ Bulletin 3 31 24
Deerfoot Church of Christ Bulletin 3 31 24
 
A MEMORIAL TRIBUTE TO THE FOUR BROTHER BILLS
A MEMORIAL TRIBUTE TO THE FOUR BROTHER BILLSA MEMORIAL TRIBUTE TO THE FOUR BROTHER BILLS
A MEMORIAL TRIBUTE TO THE FOUR BROTHER BILLS
 

[UniteKorea2013] Memory profiling in Unity

  • 1. Memory profiling in Unity Kim Steen Riber (kim@unity3d.com)
  • 2. Page Who am I? • Core developer @ Unity • Released games • LIMBO • Watchmen • Total overdose • Unity focus areas • CPU performance • Memory optimizations 09-05-2013 2
  • 3. Page Optimizing your game • FPS • CPU usage (Gamecode, Physics, Skinning, Particles, …) • GPU usage (Drawcalls, Shader usage, Image effects, …) • Hickups • Spikes in framerate caused by heavy tasks (e.g. GC.Collect) • Physics world rebuild due to moved static colliders • Memory • Maintaining small runtime memory on device • Avoid GC Hickups by reducing memory activity • Leak detection 09-05-2013 3
  • 4. Page Performance • Unity Profiler (Pro Feature) • CPU • GPU • Memory usage • New Detailed memory view (Unity 4.1) • Memory reference view (Unity 4.2) 09-05-2013 4
  • 5. Page CPU Profiler • Cpu time consumption for methods • Mono memory activity • Remote Profiling of you game running on target device • Deep profile (editor only) • Detailed view, but large overhead, only usable for very small scenes 09-05-2013 5
  • 6. Page Memory Profiler • Simple and Detailed memory view (Unity 4.1) • Detail view is taken as a snapshot (too expensive for per frame) • Reference view (Unity 4.2) • See where an object is referenced – Good for leak hunting 09-05-2013 7
  • 7. Page Memory Profiler 09-05-2013 8 • Simple memory view • Unity reserves chunks of memory from the os • Mono allocates from a reserved heap • GfxMemory is an estimate
  • 8. Page Mono vs. Unity Memory • Managed - Mono • Script objects • Wrappers for unity objects • Game objects • Assets • Components • … • Memory is garbage collected 09-05-2013 9 • Native - Unity internal • Asset data • Textures • Meshes • Audio • Animation • Game objects • Engine internals • Rendering • Particles • Webstreams • Physics • …..
  • 9. Page Mono Memory Internals • Allocates system heap blocks for allocations • Garbage collector cleans up • Will allocate new heap blocks when needed • Fragmentation can cause new heap blocks even though memory is not exhausted • Heap blocks are kept in Mono for later use • Memory can be given back to the system after a while 09-05-2013 10
  • 10. Page Fragmentation • Memory will get fragmentet if there is a lot of activity 09-05-2013 11 Mono: 16K System: 64K Mono: 32K System: 64K Mono: 32K System: 64K Mono: 48K System: 128K
  • 11. Page Avoiding Allocations • Reuse temporary buffers • If buffers for data processing are needed every frame, allocate the buffer once and reuse • Allocate pools of reusable objects • Create freelists for objects that are needed often • Use structs instead of classes • Structs are placed on the stack, while classes uses the heap • Don’t use OnGUI • Even empty OnGUI calls are very memory intensive 09-05-2013 12
  • 12. Page Avoiding Allocations • Use the CPU profiler to identify mono allocations 09-05-2013 13
  • 13. Page Unity Object wrapper • Some Objects used in scripts have large native backing memory in unity • Memory not freed until Finalizers have run 09-05-2013 14 WWW Decompression buffer Compressed file Decompressed file Managed Native
  • 14. Page Mono Garbage Collection • Object goes out of scope • GC.Collect runs when • Mono exhausts the heap space • Or user calls System.GC.Collect() • Finalizers • Run on a separate thread • Unity native memory • Dispose() cleans up internal memory • Eventually called from finalizer • Manually call Dispose() to cleanup 09-05-2013 15 Main thread Finalizer thread www = null; new(someclass ); //no more heap -> GC.Collect(); www.Dispose(); .....
  • 15. Page Garbage collect and Dispose Demo 09-05-2013 16
  • 16. Page Assetbundle memory usage • WebStream • Compressed file • Decompression buffers • Uncompressed file • Assetbundle • Map of objects and offsets in WebStream • Instantiated objects • Textures, Meshes, etc. 09-05-2013 17
  • 17. Page Assetbundle memory usage • WWW www = new WWW(assetbundle_url); • Loads the compressed file into memory • Constructs decompression buffers (8MB per file) • Decompresses the file into memory • Deallocates the decompression buffers • One decompression buffer of 8MB is reused and never deallocated 09-05-2013 18
  • 18. Page Assetbundle memory usage • AssetBundle ab = www.assetBundle; • Loads the map of where objects are in the webstream • Retains the www WebStream 09-05-2013 19 WebStream Tex Tex Mes h AssetBundle
  • 19. Page Assetbundle memory usage • AssetBundle ab = www.assetBundle; • Loads the map of where objects are in the webstream • Retains the www WebStream 09-05-2013 20 WebStream Tex Tex Mes h AssetBundle Loaded objects
  • 20. Page Assetbundle memory usage • Texture2D tex = ab.Load(“MyTex", typeof(Texture2D)); • Instantiates a texture from the assetbundle • Uploads the texture to the GPU • On editor a system copy is retained (2x memory) • Transferbuffer for the RenderThread will grow to fit the largest Texture or Vertexbuffer (never shrinks) 09-05-2013 21
  • 21. Page Assetbundle memory usage • Deleting the WebStream • www.Dispose(); // will count down the retain count • If not called, finalizers will clean the memory eventually • Deleting the Assetbundle • ab.Unload(false); • Unloads the map and counts down the www retain count • ab.Unload(true); • Will also force unload all assets created from the assetbundle 09-05-2013 22
  • 22. Page Assetbundle memory usage • Removing the loaded objects from memory • ab.Unload(true) • Force unload objects loaded by assetbundle • UnloadUnusedAssets() • Unloads when there are no more references to the object • Use the memory profiler to find remaining references • In Unity 4.1 a reason why a Object is given • In Unity 4.2 specific scripts or Objects referencing a given object are shown 09-05-2013 23
  • 23. Page Assetbundle memory usage • For best memory efficiency do one assetbundle at a time • If more assetbundles are needed at the same time, load one www object into memory at a time, to reduce decompression buffer usage 09-05-2013 24
  • 25. Page Conclusions • Avoid memory activity • Use the memory profiler to monitor memory usage • Load one WWW object at a time • Use Dispose() on objects that derive from IDisposable • Specially if they have a large native memory footprint • Use UnloadUnusedAssets() to clean up assets 09-05-2013 26

Editor's Notes

  1. Hi, My name is Kim Steen Riber, and will talk about memory profiling in Unity
  2. I work at unity as a core developer. Before joining Unity I worked on a number of games:At unity I focus primarely on Performace and memory optimizations and making tools to give you the ability to make your games as performant as posibleAnd I like my LEGOs
  3. There are several things you want to adress when optimizing your game. The obvious one ofcourse is Frames per second. This is where the user gets the smooth experience of a game that runs 30 or 60 fps. There are two limiting factors to this, namely The time the game takes on the cpu: that would be things like your gamecode, physics, skinning and other tasks that run on the cpu side. Then there is the gpu side, where things like drawcalls, shader complexity and fillrate matter. Your game will never run faster than the limiting of the 2.One other thing that can degrade the user experience is if the game has a lot of hickups. This will make the game feel stuttering. Things that can cause hickups are long running tasks like garbage collect or physics world rebuilding if for example a static collider is moved.Also memory is an imprtant thing to keep in mind when developing your game. There are 2 main reasons for this: Keeping the runtime memory low, to avoid out of memory – specially on mobile devices, and keeping the memory activity low, to avoid the garbage collecter to kick in
  4. In unity pro we have a tool for this: the unity profiler. This has several focus areas, but I will only talk about the cpu and memory profiler.In unity 4.1 and 4.2 we have added exended functionality to get a more detailed view of your memory usage
  5. The Cpu profiler will let you see the time consumption for each frame. This is displayed in a hierarchy view and can be sorted with the most timeconsuming methods at the top. This will allow you to pinpoint where you should focus your efforts when optimizing. Ther is also a column that tells how much mono memory is allocated by each entry in the profiler. I’ll get to that later.The profiler has the ability to connect to a running player on a device or on your computer. This allows you to profile the actial running game on for example an iphone or in the webplayer. This is done using the dropdown at the top ‘Active Profiler’In the editor you also have the ability to turn on deep profiling. This will instrument all calls in managed code, and will give you are more detailed callgraph. This however has a large performance overhead, so is only feasible on small scenes
  6. The GPU profiler will measure the time taken by individual drawcalls, and lets you drill down into the hierarchy to find the most timeconsuming calls. As with CPU profiling it is best to record the profile when running on device, since the overhead caused by the editor can be significant.
  7. In Unity 4.1 we have made some improvements to the memory profiler which lets you inspect memory at a much finer level than before. There is a simple view and a detailed view. The detailed view is expensive to calculate, so this is implementet as the ability to take a snapshot of the curent state.The detail view will show a list of UnityObjects like Assets and Scene objects, and will also have a calculation of some core areas of unity, like webstreams, mono managed heap, shaderlab and many more.This view will allow you to find memory consuming objects like an uncompressed or excesively large texture acidently added to your game, and focus your efforts on reducing these.In Unity 4.2 we have also implemented a reference view, which allows you to see where a given asset or gameobject is referenced from. This can help you in finding why an asset is not unloaded, by pinpointing where a script is holding a reference to it.
  8. The simple view in the memoryprofiler shows some key numbers in the used memory.It has the Used size and the reserved size of varrious parts of the engine. Both mono and Unity reserves blocks of memory ahead of time and then allocates the requested bytes from these.The GfxDriver usage is based on an estimate calculated from when textures and meshes are uploaded to the driver.
  9. As you could see on the simple memory profiler, The memory in unity is split up in managed and native memory.The managed memory is what is used from Mono, and includes what you allocate in scripts and the wrappers for unity objects.This memory is garbage collected by monoThe native memory is what Unity is allocating to hold everything in the engine. This includes Asset data like tex, mesh, audio, animation. It includes gameobjects and components, and then it covers engine internals like redering , culling, shaderlab, particles, webstreams, files, physics, etc….This memory is not garbage collected, and sometimes needs the UnloadUnusedAssets method call to be freed.
  10. The managed memory used by mono reserves a block of system memory to use for the allocations requested from your scripts. When the heapspace is exhausted, mono will run the garbage collecter to reclaim memory that is no longer being referenced.If more memory is needed mono will allocate more heap space. This will grow to fit the peak memory usage of your application. The garbage collection can be a timeconsuming operation specially on large games. This is one of the reasons to keep the memory activity low.Another reason is that with high memory activity, memory is likely to fragment and the small memory fragments will be unusable and cause memory to growWhen the memory is being freed, mono can in some cases give the heap space back to the system, although this is less likely if memory is fragmentet
  11. So the basics of fragmentation, is that, if there is a lot of allocations where some are retained and some are deleted, memory will get filled with small holes. This will look like free memory, but when trying to make a larger allocation, there is not enough contiguous memory to service that request. This means that mono will have to allocate more heap blocks even though it seams like there is enough free space.
  12. Even though scripting happens i a managed language like C#, there are a number of ways to control the memory and reduce the amount of allocations made by your code.If there are routines in your code that needs some temporary buffers to process data, it is worth considdering to keep these buffers around instead of reallocating them every time the routine is run.Another thing to considder is creating object pools if temporary objects are shortlived and needed often. An example of that could be bullets that are short lived. Having a pool of bullets and then grabbing one when needed and putting it back when done, it will save both the object instantiation and will reduce the allocation activity.A Third thing to considder is using structs instead of classes. When using structs the data is allocated on the stack instead of the heap.Also. Don’t use OnGUI since the GUIUtility will kick in.These are all things that will reduce the memory activity, and thereby reduce the need for garbage collections and fragmentation
  13. This is a small example where on the left side we have a script that needs a databuffer to process some data. It is written without regards to memory usage, as you can see it uses a class for the workdata, and the workbuffer in here is allocated every time the function runs.On the right side, is a version where the Workdata is a struct, and the workbuffer is placed on the class in order to only allocate it once and then reuse the same buffer.On the CPU profiler you can see how the Mono memory usage is excesively high in the allocating script and how a lot of time is used to allocate the workbuffer.In the non allocating script, no memory is allocated, and the script takes no time – like it should since there is not real work done.
  14. Some objects that you can allocate in scripts have large native memory footprints in unity. An example of that is the WWW class which in mono is only a small wrapper, but in Unity it contains some very large allocations. This backing memory is not cleaned up until the finalizers are run, or Dispose is called manually. If this is left to the garbage collector and the finalizers, this memory can potentially live long after the reference is removed from mono.
  15. So the way the garbage collector works is shown here.A reference is removed from mono by setting the reference to null or the object going out of scope. After a while the garbage collector will run, either because the heapspace gets exhausted, or because we manually call GC.Collect()When the memory is collected by the garbagecollector, it is put on a queue for the finalizer. This is handled by another thread, and eventually the finalizer will call Dispose on the object. At this point the unity native memory will be deallocated.To skip this roundtrip, you should call Dispose manually on the object, and then the object will not be given to the finalizers and the memory will be cleaned up imediately. I have a small example that shows this
  16. Garbage collect / Dispose DEMODEMO:Load www, set to null and notice a quick releaseIncrease heap and do the same. Notice memory will not decrease.Use detailed view to show that webstream is still around Do GC.Collect and see memory dropLoad www and use dispose. See that memory drops
  17. When using asset bundles, it is important to know what memory unity has allocated at various stages.For the webstream data there are several buffers depending on the settings of the stream. If it is a compressed stream loading from disk, it will have these buffers: The compressed file, some decompression buffers used by lzma, and the final uncompressed data.The assetbundle created from this www object, allocates a map of objects in the assetbundle and offsets in the decompressed data.When loading objects from the assetbundle, these objects will be created in memory from the decompressed data
  18. When you have your assetbundle url or file, you can load this file asynchroniously by calling new WWW(). This will load the compressed file into memory and start the decompression. The decompression algorithm will need some buffers and these will require a buffer of 8MB. The decompression will construct the unpacked data and after it is done it will deallocate its decompression buffers.To avoid that the 8MB decompression buffer is reallocated for every file being loaded, we keep one buffer in memory that we reuse.Keep in mind that several parallel loads will require more of these buffers to be allocated simultaneously and will result in a large memory spike. To avoid this, load one file at a time instead of starting multiple www requestsFor Assetbundles created with Unity 4.2 we have changed the compression a bit, which has reduced the decompression buffer requirements to half a megabyte instead.
  19. After the file is loaded, you construct the assetbundle from the file by calling www.assetBundle.This will load the map of objects and what offsets they have into the decompressed data. The assetbundle retains a pointer to the WebStream. This will prevent the data from being unloaded even if Dispose is called on the www object.
  20. When objects are loaded from the assetbundle, the data from the webstream is used to construct the requested objects. The assetbundle will hold references to these object.
  21. To loadobjects from the assetbundle, use the Load, LoadAll or mainAsset methods.In the example I will show later, I will load a texture. This will instantiate the texture from the assetbundle data. Then the texture is uploaded to the gpu, and on player builds the main data is then deallocated.On platforms that use our multithreaded renderer the texture is trasfered to the renderthread and the transfer buffer will grow to fit the texture data – I will show that later
  22. When all objects you need have been loaded from the file, you can get rid of the webstream data and the asset bundle.The www object should be deleted by calling Dispose, and not left for the garbage collector to clean up.As long as the Assetbundle is still around, the webstream will not be unloaded, so the assetbundle needs to be unloaded as well, in order to release its handle to the webstream.Unloading the assetbundle can be done by calling unload with either true or false.Calling it with false will release the webstream and delete the map in the assetbundleIf you instead call unload (true) the assetbundle will travers its list of loaded objects and destroy these as well. If there are still references to these objects in scripts, these will be null after this.
  23. When you are done using your assets, you can unload them by still having the assetbundle and calling unload(true) or you can call UnloadUnusedAssets and all assets that are no longer being referenced will be removed from memoryIf an object is not unloaded when calling unload unused assets, it is because it is still being referenced. In the profiler in unity 4.1 you will be able to see if the object is referenced from script or if it for example is marked as HideAndDontSaveIn unity 4.2 we have added additional functionality, so you can see what other objects are holding a references to your object. This should help you to find the references and unload the object
  24. So the most memory efficiency way of loading assetbundles is, If posible, to load just one assetbundle at a time, load what is needed and destroy the assetbundle again. Here is a small example that loads a texture from an assetbundle and when this coroutine exits, both webstream and assetbundle is unloaded and there is no other memory left except the instantiated texture.To, later on get rid of this texture, set the reference to null and call UnloadUnusedAssets.
  25. I have made a small example that shows the assetbundle loading and unloading, and how you can use the memory profiler to see what is happening and what memory is allocated. This is demoed on Unity 4.2 as this has some extra features, that I would also like to show you.DEMO:Load new(unity4.2) www. Notice mem increases. Dispose removes all memory againLoad old(pre 4.2) www. After dispose, there is +8MB left. Use detail view to investigate, and sow the cached buffer.Load www, ab and texture. Detail view – show webstream, assetbundle and texture. Notice the gfxClientBuffer.Dispose www -> nothing happens, because ab has retained handle.Unlead (true). See mem falls to 40MB -> gfxClient and cached decompression bufferLoad all. Unload (false) and Dispose().See detail ->Tex referenced by scriptSet tex= null see that nothing happens. See tex still in detail view, but not referencedCall unloadUnusedAssets. See gfx memory go down and tex is gone from detailed