Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove more unnecessary LINQ usage #33892

Merged
merged 1 commit into from
Mar 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,12 @@ public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T>

public static IEnumerable<T>? ConcatAllowingNull<T>(this IEnumerable<T>? source, IEnumerable<T>? second)
{
if (second == null || !second.FastAny())
if (second == null || !second.Any())
{
return source;
}

if (source == null || !source.FastAny())
if (source == null || !source.Any())
{
return second;
}
Expand Down Expand Up @@ -203,23 +203,6 @@ public static EnumerableCardinality GetCardinality<T>(this IEnumerable<T> source
}
}

public static bool FastAny<T>(this IEnumerable<T> source)
{
// Enumerable.Any<T> underneath doesn't cast to ICollection,
// like it does with many of the other LINQ methods.
// Below is significantly (4x) when mainly working with ICollection
// sources and a little slower if working with mainly IEnumerable<T>
// sources.

// Cast to ICollection instead of ICollection<T> for performance reasons.
if (source is ICollection collection)
{
return collection.Count > 0;
}

return source.Any();
}

public static Stack<T> Copy<T>(this Stack<T> stack)
{
if (stack == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public CompositionResult(IEnumerable<CompositionError>? errors)

public bool Succeeded
{
get { return _errors == null || !_errors.FastAny(); }
get { return _errors == null || !_errors.Any(); }
}

public IEnumerable<CompositionError> Errors
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ internal CompositionResult([AllowNull] T value, IEnumerable<CompositionError>? e

public bool Succeeded
{
get { return _errors == null || !_errors.FastAny(); }
get { return _errors == null || !_errors.Any(); }
}

public IEnumerable<CompositionError> Errors
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ protected override IEnumerable<Export> GetExportsCore(ImportDefinition definitio
{
bool cardinalityCheckResult = provider.TryGetExports(definition, atomicComposition, out IEnumerable<Export>? exports);
Debug.Assert(exports != null);
bool anyExports = exports.FastAny();
bool anyExports = exports.Any();
if (cardinalityCheckResult && anyExports)
{
// NOTE : if the provider returned nothing, we need to proceed, even if it indicated that the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ private void OnChangingInternal(object? sender, ComposablePartCatalogChangeEvent
e.AtomicComposition);

// Only fire if we need to
if (result.AddedDefinitions.FastAny() || result.RemovedDefinitions.FastAny())
if (result.AddedDefinitions.Any() || result.RemovedDefinitions.Any())
{
return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ public void UpdateDisposableDependencies(ImportDefinition import, Export[] expor
if (disposableExports == null)
{
_importedDisposableExports.Remove(import);
if (!_importedDisposableExports.FastAny())
if (!_importedDisposableExports.Any())
{
_importedDisposableExports = null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace System.Diagnostics
{
Expand All @@ -23,9 +22,9 @@ public void Kill(bool entireProcessTree)
if (IsSelfOrDescendantOf(GetCurrentProcess()))
throw new InvalidOperationException(SR.KillEntireProcessTree_DisallowedBecauseTreeContainsCallingProcess);

IEnumerable<Exception> result = KillTree();
List<Exception>? result = KillTree();

if (result.Any())
if (result != null && result.Count != 0)
throw new AggregateException(SR.KillEntireProcessTree_TerminationIncomplete, result);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
Expand Down Expand Up @@ -86,11 +83,11 @@ public void Kill()
private bool GetHasExited(bool refresh)
=> GetWaitState().GetExited(out _, refresh);

private IEnumerable<Exception> KillTree()
private List<Exception>? KillTree()
{
List<Exception>? exceptions = null;
KillTree(ref exceptions);
return exceptions ?? Enumerable.Empty<Exception>();
return exceptions;
}

private void KillTree(ref List<Exception>? exceptions)
Expand All @@ -111,7 +108,7 @@ private void KillTree(ref List<Exception>? exceptions)
// Ignore 'process no longer exists' error.
if (error != Interop.Error.ESRCH)
{
AddException(ref exceptions, new Win32Exception());
(exceptions ??= new List<Exception>()).Add(new Win32Exception());
}
return;
}
Expand All @@ -125,7 +122,7 @@ private void KillTree(ref List<Exception>? exceptions)
// Ignore 'process no longer exists' error.
if (error != Interop.Error.ESRCH)
{
AddException(ref exceptions, new Win32Exception());
(exceptions ??= new List<Exception>()).Add(new Win32Exception());
}
}

Expand All @@ -134,15 +131,6 @@ private void KillTree(ref List<Exception>? exceptions)
childProcess.KillTree(ref exceptions);
childProcess.Dispose();
}

void AddException(ref List<Exception>? list, Exception e)
{
if (list == null)
{
list = new List<Exception>();
}
list.Add(e);
}
}

/// <summary>Discards any information about the associated process.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
Expand Down Expand Up @@ -365,25 +364,25 @@ private bool Equals(Process process) =>
Id == process.Id
&& StartTime == process.StartTime;

private IEnumerable<Exception> KillTree()
private List<Exception>? KillTree()
{
// The process's structures will be preserved as long as a handle is held pointing to them, even if the process exits or
// is terminated. A handle is held here to ensure a stable reference to the process during execution.
using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION, throwIfExited: false))
{
// If the process has exited, the handle is invalid.
if (handle.IsInvalid)
return Enumerable.Empty<Exception>();
return null;

return KillTree(handle);
}
}

private IEnumerable<Exception> KillTree(SafeProcessHandle handle)
private List<Exception>? KillTree(SafeProcessHandle handle)
{
Debug.Assert(!handle.IsInvalid);

List<Exception> exceptions = new List<Exception>();
List<Exception>? exceptions = null;

try
{
Expand All @@ -394,16 +393,19 @@ private IEnumerable<Exception> KillTree(SafeProcessHandle handle)
}
catch (Win32Exception e)
{
exceptions.Add(e);
(exceptions ??= new List<Exception>()).Add(e);
}

IReadOnlyList<(Process Process, SafeProcessHandle Handle)> children = GetProcessHandlePairs(p => SafePredicateTest(() => IsParentOf(p)));
List<(Process Process, SafeProcessHandle Handle)> children = GetProcessHandlePairs(p => SafePredicateTest(() => IsParentOf(p)));
try
{
foreach ((Process Process, SafeProcessHandle Handle) child in children)
{
IEnumerable<Exception> exceptionsFromChild = child.Process.KillTree(child.Handle);
exceptions.AddRange(exceptionsFromChild);
List<Exception>? exceptionsFromChild = child.Process.KillTree(child.Handle);
if (exceptionsFromChild != null)
{
(exceptions ??= new List<Exception>()).AddRange(exceptionsFromChild);
}
}
}
finally
Expand All @@ -418,12 +420,28 @@ private IEnumerable<Exception> KillTree(SafeProcessHandle handle)
return exceptions;
}

private IReadOnlyList<(Process Process, SafeProcessHandle Handle)> GetProcessHandlePairs(Func<Process, bool> predicate)
private List<(Process Process, SafeProcessHandle Handle)> GetProcessHandlePairs(Func<Process, bool> predicate)
{
return GetProcesses()
.Select(p => (Process: p, Handle: SafeGetHandle(p)))
.Where(p => !p.Handle.IsInvalid && predicate(p.Process))
.ToList();
var results = new List<(Process Process, SafeProcessHandle Handle)>();

foreach (Process p in GetProcesses())
{
SafeProcessHandle h = SafeGetHandle(p);
if (!h.IsInvalid)
{
if (predicate(p))
{
results.Add((p, h));
}
else
{
p.Dispose();
stephentoub marked this conversation as resolved.
Show resolved Hide resolved
h.Dispose();
}
}
}

return results;

static SafeProcessHandle SafeGetHandle(Process process)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1040,7 +1040,7 @@ private static BlockExpression BlockCore(Type? type, ReadOnlyCollection<Paramete

return new ScopeWithType(variables, expressions, type);
}
Expression last = expressions.Last();
Expression last = expressions[^1];
if (type != typeof(void))
{
if (!TypeUtils.AreReferenceAssignable(type, last.Type))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ private void EmitSwitchBuckets(SwitchInfo info, List<List<SwitchLabel>> buckets,
// explicit guard
Label secondHalf = _ilg.DefineLabel();
_ilg.Emit(OpCodes.Ldloc, info.Value);
EmitConstant(buckets[mid - 1].Last().Constant);
EmitConstant(buckets[mid - 1][^1].Constant);
_ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, secondHalf);
EmitSwitchBuckets(info, buckets, first, mid - 1);
_ilg.MarkLabel(secondHalf);
Expand Down Expand Up @@ -582,7 +582,7 @@ private void EmitSwitchBucket(SwitchInfo info, List<SwitchLabel> bucket)
{
after = _ilg.DefineLabel();
_ilg.Emit(OpCodes.Ldloc, info.Value);
EmitConstant(bucket.Last().Constant);
EmitConstant(bucket[^1].Constant);
_ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, after.Value);
_ilg.Emit(OpCodes.Ldloc, info.Value);
EmitConstant(bucket[0].Constant);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ private static bool IsDuringExpiresAttributeParsing(string singleValue)
// Current cookie doesn't contain any attributes.
if (!singleValue.Contains(';')) return false;

string lastElement = singleValue.Split(';').Last();
string lastElement = singleValue.Split(';')[^1];
bool noComma = !lastElement.Contains(',');

string lastAttribute = lastElement.Split('=')[0].Trim();
Expand Down