Performance recommendations for Unity - nicebug/nicebug.github.io GitHub Wiki

[Performance recommendations for Unity] (https://developer.microsoft.com/en-us/windows/holographic/performance_recommendations_for_unity)

Unity性能优化建议

CPU Performance

cpu性能优化

for CPU performance are:

  • Too many objects being rendered (try to keep this under 100 unique Renderers or UI elements)
  • Expensive updates or too many object updates
  • Hitches due to garbage collection
  • Expensive graphics settings and shaders (shadows, reflection probes, etc.)
cpu性能瓶颈通常出现在:
1. 太多的对象需要被渲染(保持该项低于100个特有渲染器或者UI元素)
2. update更新太复杂或则太多元素更新
3. GC导致的cpu热点
4. 图像设置或着色器设置不合理(比如阴影,反射探头等)

Garbage collections

While the GC doesn't typically contribute all that much to overall cycles spent or power usage, it does cause unpredictable spikes that can make you drop several frames in a row which leads to holograms looking "glitchy" or unstable.

尽管GC并不贡献那么多的周期消耗或者电量消耗,但它会导致不可预期的峰值使得你的程序掉一些帧,使得你的holograms看起来有故障的,不稳定的

A key aspect of managing the GC is to plan for it up front. It's usually much harder to fix high GC usage after-the-fact than it is to take some extra care up front.

管理GC的一个关键点是提前计划。事后关注GC高使用率问题相对于提前采取措施通常是难以修复的。

Tips for avoiding allocations. The ideal way to avoid allocations (and thus collections) is to allocate everything you need at the startup of the application and just reuse that data while the app runs. There are plenty of cases where it's not possible to avoid allocations (for example APIs that return allocated objects), so this isn't actually possible in practice, but it's a good goal to shoot for.

There are also some unintuitive reasons why allocations may occur even when you're not directly allocating something, here are some tips to avoid that:

  • Do not use LINQ, as it causes heavy allocations.
  • Do not use lambdas, as they cause allocations.
  • Beware of boxing! A common case for that is passing structs to a method that takes an interface as a parameter. Instead, make the method take the concrete type (by ref) so that it can be passed without allocation.
  • Prefer structs to classes whenever you can.
  • Default implementations for value equality and GetHashcode uses reflection, which is not only slow but also performs a lot of allocations.
  • Avoid foreach loops on everything except raw arrays. Each call on a non-array allocates an Enumerator. Prefer regular for loops whenever possible.
有一些原因可能导致即使你不直接分配内存,也可能导致临时内存的分配。以下是一些规避这些临时内存分配的建议:

1. 不要使用LINQ,它可能导致严重的内存分配
2. 不要使用lambdas匿名函数,他们可能导致内存分配
3. 小心装箱问题!一种常见的情况是将结构体作为参数传递给一个方法,一个接口。相反,应该使该方法采用具体的类型,以便他可以在传递时没有内存分配
4. 尽可能使用结构体而不是类
5. 值相等和GetHashcode方法默认实现使用的反射,这不仅导致函数执行慢,而且会导致大量的内存分配
6. 除了原始数组外避免在其他类型上使用foreach。每次调用非数组类型都会分配一个枚举器。尽量使用for循环