版本是用的Unity的2019.4的版本,因为Ecs的版本更新太快,api更新太频繁,所以学习起来是比较的麻烦,而且教程也是有限
ECS快的原因
需要去了解dots,推荐大家看一看这个视频 DOTS从原理到应用-雨松MOMO
首先如果学过计算机组成原理或者操作系统应该知道,计算机的存储层次最快的为cpu寄存器,往下是主存,但是主存的访问速度与cpu的处理速度相差太远,于是在二者之间加了一个高速缓存来解决这个问题
ECS所做的工作,就是来提高缓存的命中率
当我们使用面向对象编程的时候,各个对象引用各个对象,使得数据在内存中分布是分散的,但在是ECS中 组件使用的是结构体,结构体的内存是分配在栈上的,这就是的数据的在内存中的分配是比较连续的
ECS只是Dots中的一部分,Dots是由ECS Jobsystem(管理多线程) 和Burst(对c#代码进行高度优化)组成
Jobsystem和Burst性能测试
新建一个test脚本,写入一下的代码,把脚本挂载到物体上,然后测试
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using Unity.Transforms;
using Unity.Collections;
using Unity.Rendering;
using Unity.Mathematics;
using Unity.Jobs;
using UnityEngine.Jobs;
using Unity.Burst;
class Testing : MonoBehaviour
{
[SerializeField] private bool useJobs;
private void Update()
{
float startTime = Time.realtimeSinceStartup;
if (!useJobs)
{
for(int i = 0; i < 10; i++)
{
ReallyToughTask();
}
}
else
{
NativeList<JobHandle> jobHandleList = new NativeList<JobHandle>(Allocator.Temp);
for(int i = 0; i < 10; i++)
{
JobHandle jobHandle = ReallyToughTaskJob();
jobHandleList.Add(jobHandle);
}
JobHandle.CompleteAll(jobHandleList);
jobHandleList.Dispose();
}
Debug.Log((Time.realtimeSinceStartup - startTime) * 1000);
}
/// <summary>
/// 不使用作业系统
/// </summary>
private void ReallyToughTask()
{
float v = 0f;
for(int i = 0; i <= 10000; i++)
{
v = math.exp10(math.sqrt(v));
}
}
/// <summary>
/// 使用作业系统
/// </summary>
/// <returns></returns>
private JobHandle ReallyToughTaskJob()
{
ReallyToughJob job = new ReallyToughJob();
return job.Schedule();
}
}
[BurstCompile]
public struct ReallyToughJob : IJob
{
void IJob.Execute()
{