Anyone know which one of the following is faster. Applying script #1 onto 10 objects, or using script #2 on one object but applying 10 transforms to the variable?
function Update () {
transform.Translate (1, 0, 0);
}
var targets : Transform[];
function Update () {
for (int i = 0; i < targets.Length; ++i)
targets [i].Translate (1, 0, 0);
}
First of all stop using UnityScript if you are really concerned about performance. In real projects and in long term the latter is faster because you speed up execution of script by caching the reference which is used many times (in addition to what Eric said).
That’s what I was thinking, but when I go to the next step and ask myself: “Okay then, why don’t we just have 1 script with Update, which calls ‘OnUpdate’ on every other script” (instead of having every script have it’s own update). If you are right, Eric, then why wouldn’t everyone just do this:
var targets : CustomMonoBehaviour[];
function Update () {
for (var i = 0; i < targets.Length; ++i)
targets [i].OnUpdate ();
}
Good point, sadly it’s still a bit of a weak spot of my Unity knowledge.
The code I posted was pseudo code, and I used javascript because it was quicker to type (kind of irrelevant); And I’m not worried about caching either. My main question is, are 1,000,000 separate scripts with Update() slower than one script with Update() that does all the same stuff?
That makes no sense. It’s not any slower than C# in general.
Yes I’m right; you can easily see for yourself by using the profiler or just do benchmarking if you don’t have Pro. As to why not, because it’s more complicated and as I said doesn’t necessarily actually gain any real performance. If you have a huge number of objects, then it’s generally a good idea, otherwise keep it simple.
Definitely vote against using a delegate system to call your all your updates from one script, the performance gains of 50+ update statements is not much (even on iPhone 3GS) but the headache it causes when you try to debug is massive.
That’s interesting trooper, but what about some of the other ones. Like would it be cheaper to have one script that has OnGUI in it, which calls OnGUI on all the other scripts that need it (instead of every script having it’s own OnGUI)? As I recall reading that every OnGUI call is quite expensive…