example of optimization in C # removing empty elements from List

Source: Internet
Author: User


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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.