Skip to content
This repository has been archived by the owner on Jan 23, 2023. It is now read-only.

Commit

Permalink
Faster List Add & Clear
Browse files Browse the repository at this point in the history
  • Loading branch information
benaadams committed Feb 12, 2017
1 parent 52a816d commit 2601c83
Showing 1 changed file with 22 additions and 8 deletions.
30 changes: 22 additions & 8 deletions src/mscorlib/src/System/Collections/Generic/List.cs
Expand Up @@ -12,14 +12,16 @@
**
**
===========================================================*/
namespace System.Collections.Generic {

using System.Reflection;

namespace System.Collections.Generic
{
using System;
using System.Runtime;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;

// Implements a variable-size List that uses an array of objects to store the
// elements. A List has a capacity, which is the allocated length
Expand Down Expand Up @@ -208,9 +210,15 @@ public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
//
public void Add(T item) {
if (_size == _items.Length) EnsureCapacity(_size + 1);
_items[_size++] = item;
public void Add(T item)
{
var size = _size;
if (size == _items.Length)
{
EnsureCapacity(size + 1);
}
_size = size + 1;
_items[size] = item;
_version++;
}

Expand Down Expand Up @@ -291,10 +299,15 @@ public int BinarySearch(T item, IComparer<T> comparer)


// Clears the contents of List.
public void Clear() {
public void Clear()
{
if (_size > 0)
{
Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
if (JitHelpers.ContainsReferences<T>())
{
Array.Clear(_items, 0, _size); // Clear the elements so that the gc can reclaim the references.
}

_size = 0;
}
_version++;
Expand Down Expand Up @@ -388,6 +401,7 @@ bool System.Collections.IList.Contains(Object item)
// value. If the current capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min,
// whichever is larger.
[MethodImpl(MethodImplAttributes.NoInlining)]
private void EnsureCapacity(int min) {
if (_items.Length < min) {
int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2;
Expand Down

0 comments on commit 2601c83

Please sign in to comment.