(2) New Features of Unity5.0 ------ internal unity: memory and performance (and Unity5 upgrade and optimization), unity5

Source: Internet
Author: User
Tags failover unity 5

(2) New Features of Unity5.0 ------ internal unity: memory and performance (and Unity5 upgrade and optimization), unity5

In our script code, we often need to access the gameObject reference or reference a component. The best way is to cache all these potentially accessed items during the Awake script.To access an attribute of a temporary gameObject instance or a gameObject instance of a temporary component,Make sure that the component exists.[RequireComponent (typeof (AudioSource)] if it is not automatically added, it cannot be removed!Can be accessed using properties. After all, attribute access is twice faster than GetComponent.However, if you cannot determine whether a component exists or even determine whether a component exists, do not use the GetComponent instead of empty attribute access results, the cost saved here is not half past one. In unity5, you have no choice, because you have no attribute accessors. Let's take a look at the comparison of the GameObject class. (Versions 4.6 and 5.0)
Inside unity: memory and PerformanceTopics
• Invalid Memory Overview
• Collect Garbage Collection
•   Mesh Internals
• Logging Scripting
• Memory Job System 1. Memory OverviewMemory Domains Memory domain
• Asynchronous Native (internal) Local (internal)
• Replicasset Data: Textures, AudioClips, and Meshes
• Invalid Game Objects & Components: Transform, etc ..
• Internal Engine Internals: Managers, Rendering, Physics, etc ..
• Managed-Mono
• Manage Script objects (Managed dlls)
• Program Wrappers (Packaging class) for Unity objects: Game objects, assets, components • program Native Dlls
• Login User's dlls and external dlls (for example: DirectX)

Native Memory: Internal Allocators local Memory: Internal distributor
• Revoke Default
•   GameObject
•   Gfx graphics and rendering
• Extends Profiler event probes
5. x: the API exposed by the local distributor in the Dll
Memory Managed by Managed Memory
• Primitive Value types (bool, int, float, struct,...) • exist in stack memory. Unallocate when removed from the stack. No GC. • Category Reference types (classes) Reference type (class)

• It exists on the stack and is deleted by mono/. net GC when it is no longer referenced for a long time. • Containers are packaged as Unity Objects:
•   GameObject
•   Assets: Texture2D, AudioClip, Mesh ,...
• Inclucomponents: MeshRenderer, Transform, MonoBehaviour
Mono Memory Internals
• Allocate Allocates system heap blocks for internal allocator (allocate system heap blocks to internal distributors)
• Allocate Will allocate new heap blocks when needed (new heap blocks Will be allocated as needed)
• Writable Heap blocks are kept in Mono for later use (the Heap block will be used later in Mono)
• Memory can be given back to the system after a while (the Memory can be handed back to the system for a period of time) • ...... but it depends on the platform, don't count on it
• Garbage collector cleans up (Garbage collector cleanup)
• Failover Fragmentation can cause new heap blocks even though memory is not exhausted (fragments can lead to new heap blocks even if the memory is not used up)
Ii. Garbage Collection Unity Object wrapper (encapsulation)• Define Some Objects used in scripts have large native backing memory in unity (Some Objects used in scripts in unity have a large number of local memory support)
• Memory will not be released until the Finalizers Terminator is run

Mono Garbage Collection• Collect GC. Collect
• Running Runs on the main thread when (run on the main thread as follows:
• Mongomono exhausts the heap space (Mono consumes heap space)
• Users Or user callsystem. GC. Collect () (Or the user calls System. GC. Collect ())
• Initialize Finalizers Terminator
• Perform Run on a separate thread (Run on a separate thread to be fooled:
• Delayed Controlled by mono (Controlled by mono • Could Can have several seconds delay (with latency of several seconds)
• Unity native memory (unity local memory)
• Define Dispose () cleans up internal memory (Dispose () cleans up internal memory
• Using Eventually called from finalizer (called from finalizer Terminator
• Manually call Dispose () to cleanup (Manually call Dispose () to clear
Garbage Collection
• Specified Roots are not collected in a GC. Collect (the Roots will not be collected on GC. Collect)
• Managing Thread stacks • Managing CPU Registers • Managing GC Handles (used by Unity to hold onto managed objects) GC handle (using Unity to hold hosted objects) • static variables !!
• Collection Time Scale and managed heap size
• The more you allocate, the slower gets.

GC: Best Practices
• Reuse objects. Use object pools (Reuse object, Use object pool)
• Scheduler prefers stack-based allocation. Use structure instead of class
• System. GC. Collect can be used to trigger collection
• Manually call Dispose to clear immediately
Avoid temp allocations Avoid temporary allocation
• Login Don't use FindObjects or LINQ
• Please Use StringBuilder for string concatenation
• Reuse large temporary work buffers (Reuse a large number of temporary work buffers)
• Optional ToString ()
• Use the CompareTag () method instead of Rule. tag.

Unity API Temporary Allocations (Temporary Allocation)
Some examples:
• Repeated GetComponents <T>
•   Vector3 [] Mesh. vertices
•   Camera [] Camera. allCameras
• Define foreach
• Specified does not allocate by definition (definition will not be assigned) • specified However, there can be a small allocation, depending on the implementation. getEnumerator () • However, according to the specific. the GetEnumerator () implementation may have a small allocation of small.
5. x: The new non-allocation non-allocating version is being studied.
Memory fragmentation Memory fragments
• Memory fragmentation is hard to account for (Memory fragments are hard to explain)
•   Fully unload dynamically allocated content (Fully unmount the dynamically allocated content) • switch to a blank scene before next level
• Please This scene cocould have a hook where you may pause the game long enough to sample if there is anything significant in memory
• Define Ensure you clear out variables so GC. Collect will remove as much as possible
• Make sure that you clear the variable and GC. Collect will delete as many as possible • Avoid allocation as much as possible
• Reuse objects in scene play as much as possible
• Clear them out for map load to clean the memory (load the memory map)
Unloading Unused Assets unmount Unused Assets
• Garbage Resources. UnloadUnusedAssets will trigger asset garbage collection
• He searches for all unreferenced assets and uninstalls them • he is an async operation Asynchronous operation • it loading a level and is called internally
• Resources. UnloadAsset is the best
• You Need To Know Exactly What You Need Unload to uninstall • Unity does not have to scan all
• Unity 5.0: multi-threaded asset garbage collection
3. Mesh Internals Mesh Read/Write Option
• Modify it allows you to modify the mesh at runtime • if enabled is enabled, the system copies of the Mesh will be kept in the memory • reset enabled is the default
• In some cases, disabling this option will not reduce memory usage
• Elastic Skinned meshes skin mesh • elastic iOS
Unity 5.0: disable by default is disabled by default-under consideration
Non-Uniform scaled Meshes uneven scaling Grid
We need to convert the vertex normal correctly.
• Unity 4.x:
• Transform the transform mesh on the CPU • create additional data copies
• Keep Unity 5.0
• Scale Scaled on the GPU • No additional memory is needed
Static BatchingWhat is this?
• Optimize it is optimized to reduce the number of draw CILS and state changes. How does one use it?
• The player settings + Tag object is static. As follows:
How does it work internally?
• Failover Build-time generation time: Vertices are transformed to world-space Vertices converted to world space • failover Run-time Run time: index buffer is created with indices of visible objects Index buffer creation and Index of visible object Unity 5.0:
• Repeated Re-implemented static batching without copying of index buffers implements static batching again without replicating the index Buffer Dynamic BatchingWhat is this?
• Similar to static ingredients, the runtime object is non-static
How does it work?
• Adjust in player settings • adjust no need to tag. it auto-magically works... No need to mark. It automatically and magically works... how does it work internally?
• Convert objects are transformed to world space on the object to the world space
CPU
• Create a temporary VB & IB
• Rendering Rendered Unity 5.xin a draw call: We are considering making each platform parameter

Mesh Skinning
Based on different platform implementations:
• Ikex86: SSE
• Upgrade iOS/Android/WP8: Neon optimizations
• Mongod3d11/XBoxOne/GLES3.0: GPU
• Drawing XBox360, WiiU: GPU (memexport)
• Unzip PS3: SPU
•   WiiU: GPU w/stream out
Unity 5.0: Skinned meshes uses less memory through the index buffer between shared instances
4. Scripting (important !) Unity 5.0: Mono• Upgrade No upgrade cannot be upgraded
• Major bugs fixed in javasmainly bug fixes
• New tech in WebGL: IL2CPP New Technology in WebGL: IL2CPP
Http://blogs.unity3d.com/2014/04/29/on-the-future-of-web-publishing-in-unity/
• Please visit: there will be blog posts about it GetComponent <T>
It requires a game object to get a specified type of component:
• Configure The GO contains a list of Components
• GO contains a list of Components • Each component type is compared to T
• The type T (or derived from T) of the first component will be returned to the caller
• Not much overhead, but it still needs to be transferred to the local code Unity 5.0: Accessors of the Property
• Most accessors will be removed in Unity 5.0 • The purpose is to reduce dependencies and therefore improve modularity
• Transform will still be retained • Existing scripts will be converted. Example: in 5.0:
Transform Component
• This. transform is the same as GetComponent <Transform> ().
• Required transform. position/rotation:
• Extract find Transform component • Extract Traverse hierarchy to calculate absolute position traversal level to calculate absolute position • Extract Apply translation/rotation
• Transform internally stores the position relative to the parent transform the location in the internal storage is relative to the parent level
• Implements transform. localPosition = new Vector (...) → Simple assignment • 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 = new Vector (...) →if There is no father, the cost will be the same; otherwise, it will need to traverse hierarchy locally to obtain the absolute value of the transform position.
• Other components will be notified via messages (collision body, rigid body, lightweight, camera ,).
Instantiate
API:
• Jsonobject Instantiate (Object, Vector3, Quaternion); • jsonobject Instantiate (Object );
Implementation execution:
• Clone GameObject Hierarchy and Components • duplicate Copy Properties • mongoawake • Apply new Transform (if provided) applies to new transformations (if provided)
Instantiate cont.. ed
• Mongoawake can be expensive
• AwakeFromLoad (main thread)
• Clear states cleaning status • internal state caching internal state cache • pre-compute pre-Calculation
In Unity 5.0:
•   Allocations have been balanced CED allocation has been reduced • some internal loops are used to optimize the replicated data
JIT Compilation ( JIT compilation)
What is this?
• Generate machine code from the pencil code in the process, during which the application is running
Pros: advantages:
• For the current platform, it generates Optimized Code Cons: disadvantages:
• Effeceach time a method is called for the first time, the application will suffer a certain performance penalty because of the compilation
• When each method is called for the first time, the application will be subject to certain performance penalties due to assembly JIT compilation spikes
How about pre-JITting? • RuntimeHelpers. PrepareMethod won't work:
... MethodHandle. GetFunctionPointer () is better
V. Job System Unity 5.0: Job System (internal)
Job system goals: • multithreading-based code can easily write highly efficient jobs • handle The jobs shocould be able to run safely in parallel to script code
• Jobs should be able to run script code in parallel safely Job System: What is it?• It is a Framework that we plan to use in existing and new subsystems • We want Animation, NavMesh, Occlusion, Rendering, and so on. • this will eventually lead to better performance.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.