Is List Remove fast ?

Hi,

to remove an enemy from a list i was doing something like this

for (int i=0; i<myList.Count; i++) {
     if (myList[i] == this.transform) {
          myList.RemoveAt(i);
          break;
     }
}

Until i discover that

myList.Remove(this.transform);

was doing the exact same thing…
I was used to Action Script 3 where you have to do it by hand hehe.

They are doing pretty much the same thing but how faster is myList.Remove ?
Is it CPU heavy method ?

Also if i want to compare 2 method speed in miliseconds, how can i do that ?
Thank you in advance for any feedback.

Best Regards.

Your version should be much slower, as you use this.transform which does internally a GetComponent() or at least a WrapperLessCall to the native code, which does the same thing or better returns the transform which is always present in a quicker way. I each case its still a wrapperless call, an extra call. Which will be done.

If you precache this.transform and use the cached value, it should be equal speeded.

Oh i see!
So, right now, i am not getting any speed benefit because i use this.transform in both case ?

What do you mean by cached value ?

Do you mean put this.transform in a variable ?

void Start() {
     Transform t = this.transform;
}

myList.Remove(t);

Is this pseudo code the way to get ride off extra call you are talking about ?

Thank you anyway for taking time to answer.
Always appreciated.

Use t as member and not as local variable and this will work :wink:

For the real performance differences you should build up a small benchmark to look it up yourself to be sure :wink:

this.transform seems like it would be a quick reference lookup, but from everything I read that is just not the case.

So in your original for loop, you were looking up this.transform every loop. Which means you looked up the transform myList.Count times. The speed increase comes from not getting this.transform over and over again, but only a single time and sticking the reference in Transform t.

Once you have cached a reference to the transform, it shouldn’t matter if you use myList.Remove(t) or step through it in a for loop.

EDIT: For something like this I would use whatever code is easier to read and maintain.