Some common performance issues are occasionally found in code reviews and recorded here.
Demand
We sometimes need to delay the deletion of the elements in the list<t>, when the element is set to null and all the empty elements are removed at once.
Before optimization
static void Removenull<t> (List<t> List) {
for (int i = list. Count-1; I >= 0; i--)
if (list[i] = = null)
List. RemoveAt (i); O (N)
}
Since RemoveAt () is the operation of time, the entire function is. But this problem only takes time.
After optimization
You can do this simply by moving the non-empty element after the first empty element forward.
static void Removenull<t> (List<t> List) {
Find the first empty element O (n)
int count = list. Count;
for (int i = 0; i < count; i++)
if (list[i] = = null) {
Record Current position
int newcount = i++;
For each non-empty element, copy to the current position O (n)
for (; i < count; i++)
if (List[i]!= null)
list[newcount++] = List[i];
Remove extra element O (n)
List. RemoveRange (Newcount, Count-newcount);
Break
}
}
List<t> actually provides removeall (predicate<t>) interface (reference implementation) to accomplish the same work. But in the current Unity of the Il2cpp, due to the delegate of the cost of the call, the realization will be slightly faster.
C + + can be std::remove, std::remove_if, because the call cost is not considered in support of inline.