-
Notifications
You must be signed in to change notification settings - Fork 136
Description
Hello again,
I've noticed functions returning components are surprisingly slow: GetComponent<>(), GetTransform() and AddComponent<>() seem to take significantly more time in C++ than they do in C#.
I've benchmarked with those two scripts:
C#:
int numObjsToInstantiate = 2500;
GameObject go;
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i=0; i<numObjsToInstantiate; i++)
{
go = new GameObject();
go.GetComponent<Transform>().parent = transform;
go.AddComponent<MeshFilter>();
go.AddComponent<MeshRenderer>();
}
sw.Stop();
print("Elapsed time: " + sw.ElapsedMilliseconds);
C++
int numObjsToInstantiate = 2500;
std::clock_t start = std::clock();
for (int i = 0; i<numObjsToInstantiate; i++)
{
GameObject go;
go.GetComponent<Transform>().SetParent(GetTransform());
go.AddComponent<MeshFilter>();
go.AddComponent<MeshRenderer>();
}
float diff = (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000);
char buf[256];
sprintf(buf, "Elapsed time: %d ms", (int)diff);
Debug::Log(String(buf));
The C# script runs in roughly 30 milliseconds. The C++ one takes 20 seconds.
I'm using Unity as a scene viewer for data from an old game, meaning I'm building the whole scene in Start() and adding a few hundred/thousands of components, setting parents for transforms, etc. In my case it's no big deal since it only runs once, but I thought the difference was a bit strange.
(I had no performance issue with other parts of the Unity API. I'm even able to load hundreds of textures in less than a second, which is a real delight.)