# Performance optimization recommendations and best practices

This chapter mainly introduces the best practices and performance optimization strategies for common interfaces.

Before reading, you can browse Overall Architecture of 2D System to understand the general operating mechanism.

Normally, since most of the logic is processed on the client side, the performance consumption of the two-dimensional part is not very high.

In most cases, the main overhead is: parsing, construction, and traversal update.

# Optimization suggestions

# Render node reuse

Instantiating Prefab will trigger the node tree construction and component deserialization assignment, which will involve the creation of client components, and the cost will be higher than attribute updates.

# Render node reuse practice

Recycle the "instantiated Prefab node" and hang it in a non-active subtree. When it needs to be used, move the entire Prefab back to the scene.

# Traversal optimization (addition and deletion of nodes)

The two-dimensional world usually has a large number of two-dimensional nodes. The addition or deletion of a certain rendering node will affect the change of the rendering order of the entire two-dimensional world, and will cause the rendering queue to be re-traversed.

# Traversal Optimization Practice-Separation of Dynamic and Static

Use UILayer component to distinguish frequently added and deleted nodes in a specific subtree.

# Drawing optimization

The cost of drawing-the number of DrawCalls

# Automatic batching strategy

Before rendering, the client will determine whether it can be combined in batches according to the adjacent rendering elements, material (rendering type, texture), rendering state (cropping state, blending state), and combining multiple renderings into one .

# Automatic batching practice

As far as possible, the rendering elements of the same type and using the same texture are placed in adjacent rendering order.

# GC (garbage collection) optimization

Due to the weakly typed language feature of Javascript, temporary objects need to be recycled, which may cause the game to drop frames.

GC Time: The total number of objects in the game

GC frequency: the number of temporary objects in the game

# GC (garbage collection) optimization practice

  • The rendering component does not use the object acquisition interface (position, color,...) as much as possible, but uses the object property acquisition interface (positionX...), or only calls the object's setter.
  • Try not to create temporary objects as much as possible, and use global temporary object assignments (Vector2, Color...)