Skip to content

Commit

Permalink
Run some built-in .NET SDK perf analyzers over several WPF assemblies (
Browse files Browse the repository at this point in the history
…#6274)

* CA2251 on PresentationCore (use string.Equals instead of string.Compare == 0)

* CA1846 on PresentationCore (use AsSpan instead of Substring)

* CA1840 on PresentationCore (use Environment.CurrentManagedThreadId)

* CA1825 on PresentationCore (avoid zero-length array allocations)

* CA1802 on PresentationCore (make constants const)

* CA1834 on PresentationCore (use StringBuilder.Append(char) instead of Append(string))

* CA2249 on PresentationCore (use Contains instead of IndexOf != -1)

* CA2249 on PresentationFramework

* CA1834 on PresentationFramework (StringBuilder.Append)

* CA1845 on PresentationFramework (string.Concat with Substring)

* CA1847 on WindowsBase (use Contains(char))

* CA1840 on WindowsBase (use Environment.CurrentManagedThreadId)

* CA1825 on WindowsBase (empty array allocation)

* CA1834 on WindowsBase (StringBuilder.Append(char))

* More StringBuilder.Append fixes (including generator files)

Co-authored-by: Dipesh Kumar <85861525+dipeshmsft@users.noreply.github.com>
  • Loading branch information
stephentoub and dipeshmsft authored Aug 10, 2022
1 parent 4912f48 commit abd651a
Show file tree
Hide file tree
Showing 78 changed files with 263 additions and 263 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ private static string GenerateStringFromFileNames(ITaskItem[] fileItemList)
for (int i = 0; i < fileItemList.Length; i++)
{
sb.Append(fileItemList[i].ItemSpec);
sb.Append(";");
sb.Append(';');
}

fileNames = sb.ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ internal static void HandleWebResponse(WebResponse response)
// associated with it. (WebHeaderCollection's internal storage is a string->ArrayList(of string) map.)
for (int i = headers.Count-1; i >= 0; i--)
{
if (string.Compare(headers.Keys[i], "Set-Cookie", StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(headers.Keys[i], "Set-Cookie", StringComparison.OrdinalIgnoreCase))
{
string p3pHeader = httpResponse.Headers["P3P"];
foreach (string cookie in headers.GetValues(i))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ internal static Uri SiteOfOrigin
if (_traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
System.Threading.Thread.CurrentThread.ManagedThreadId +
Environment.CurrentManagedThreadId +
": SiteOfOriginContainer: returning site of origin " + siteOfOrigin);
#endif

Expand Down Expand Up @@ -230,7 +230,7 @@ protected override PackagePart GetPartCore(Uri uri)
if (_traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
System.Threading.Thread.CurrentThread.ManagedThreadId +
Environment.CurrentManagedThreadId +
": SiteOfOriginContainer: Creating SiteOfOriginPart for Uri " + uri);
#endif
return new SiteOfOriginPart(this, uri);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ protected override Stream GetStreamCore(FileMode mode, FileAccess access)
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
System.Threading.Thread.CurrentThread.ManagedThreadId +
Environment.CurrentManagedThreadId +
": SiteOfOriginPart: Getting stream.");
#endif
return GetStreamAndSetContentType(false);
Expand All @@ -68,7 +68,7 @@ protected override string GetContentTypeCore()
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
System.Threading.Thread.CurrentThread.ManagedThreadId +
Environment.CurrentManagedThreadId +
": SiteOfOriginPart: Getting content type.");
#endif

Expand Down Expand Up @@ -96,7 +96,7 @@ private Stream GetStreamAndSetContentType(bool onlyNeedContentType)
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
System.Threading.Thread.CurrentThread.ManagedThreadId +
Environment.CurrentManagedThreadId +
": SiteOfOriginPart: Getting content type and using previously determined value");
#endif
return null;
Expand All @@ -112,7 +112,7 @@ private Stream GetStreamAndSetContentType(bool onlyNeedContentType)
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
System.Threading.Thread.CurrentThread.ManagedThreadId +
Environment.CurrentManagedThreadId +
"SiteOfOriginPart: Using Cached stream");
#endif
Stream temp = _cacheStream;
Expand All @@ -126,7 +126,7 @@ private Stream GetStreamAndSetContentType(bool onlyNeedContentType)
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
System.Threading.Thread.CurrentThread.ManagedThreadId +
Environment.CurrentManagedThreadId +
": SiteOfOriginPart: Determining absolute uri for this resource");
#endif
string original = Uri.ToString();
Expand All @@ -139,7 +139,7 @@ private Stream GetStreamAndSetContentType(bool onlyNeedContentType)
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
System.Threading.Thread.CurrentThread.ManagedThreadId +
Environment.CurrentManagedThreadId +
": SiteOfOriginPart: Making web request to " + _absoluteLocation);
#endif

Expand All @@ -165,7 +165,7 @@ private Stream HandleFileSource(bool onlyNeedContentType)
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
System.Threading.Thread.CurrentThread.ManagedThreadId +
Environment.CurrentManagedThreadId +
": Opening local file " + _absoluteLocation);
#endif
if (_contentType == MS.Internal.ContentType.Empty)
Expand All @@ -189,7 +189,7 @@ private Stream HandleWebSource(bool onlyNeedContentType)
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
System.Threading.Thread.CurrentThread.ManagedThreadId +
Environment.CurrentManagedThreadId +
": Successfully retrieved stream from " + _absoluteLocation);
#endif

Expand All @@ -199,7 +199,7 @@ private Stream HandleWebSource(bool onlyNeedContentType)
if (SiteOfOriginContainer._traceSwitch.Enabled)
System.Diagnostics.Trace.TraceInformation(
DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
System.Threading.Thread.CurrentThread.ManagedThreadId +
Environment.CurrentManagedThreadId +
": SiteOfOriginPart: Setting _contentType");
#endif

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ private static Text.TextInterface.FontCollection GetFontCollectionFromFileOrFold
}

// If the directory specifed is the windows fonts directory then no need to reenumerate system fonts.
if (String.Compare(((localPath.Length > 0 && localPath[localPath.Length - 1] != Path.DirectorySeparatorChar) ? localPath + Path.DirectorySeparatorChar : localPath), Util.WindowsFontsUriObject.LocalPath, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals((localPath.Length > 0 && localPath[localPath.Length - 1] != Path.DirectorySeparatorChar) ? localPath + Path.DirectorySeparatorChar : localPath, Util.WindowsFontsUriObject.LocalPath, StringComparison.OrdinalIgnoreCase))
{
return SystemFontCollection;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ internal static bool IsLegacyArabicFont(string familyName)
{
for (int i = 0; i < _legacyArabicFonts.Length; ++i)
{
if (String.Compare(familyName, _legacyArabicFonts[i], StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(familyName, _legacyArabicFonts[i], StringComparison.OrdinalIgnoreCase))
{
return true;
}
Expand Down Expand Up @@ -270,7 +270,7 @@ private static int GetIndexOfFamily(string familyName)
{
for (int i = 0; i < _systemCompositeFontsNames.Length; ++i)
{
if (String.Compare(_systemCompositeFontsNames[i], familyName, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(_systemCompositeFontsNames[i], familyName, StringComparison.OrdinalIgnoreCase))
{
return i;
}
Expand Down Expand Up @@ -396,7 +396,7 @@ ref FontStretch fontStretch
else
{
// store the stripped off style names to look for the specific face later.
potentialFaceName.Insert(0, familyName.Substring(indexOfSpace));
potentialFaceName.Insert(0, familyName.AsSpan(indexOfSpace));
familyName = familyName.Substring(0, indexOfSpace);
}

Expand Down Expand Up @@ -447,7 +447,7 @@ private CompositeFontFamily LookUpUserCompositeFamily(string familyName)
{
foreach (KeyValuePair<XmlLanguage, string> localizedFamilyName in compositeFamily.FamilyNames)
{
if (String.Compare(localizedFamilyName.Value, familyName, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(localizedFamilyName.Value, familyName, StringComparison.OrdinalIgnoreCase))
{
return compositeFamily;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -545,7 +545,7 @@ internal static bool IsSupportedFontExtension(string extension, out bool isCompo
for (int i = 0; i < SupportedExtensions.Length; ++i)
{
string supportedExtension = SupportedExtensions[i];
if (String.Compare(extension, supportedExtension, StringComparison.OrdinalIgnoreCase) == 0)
if (string.Equals(extension, supportedExtension, StringComparison.OrdinalIgnoreCase))
{
isComposite = (i == 0); // First array entry is *.CompositeFont
return true;
Expand All @@ -557,7 +557,7 @@ internal static bool IsSupportedFontExtension(string extension, out bool isCompo

internal static bool IsCompositeFont(string extension)
{
return (String.Compare(extension, CompositeFontExtension, StringComparison.OrdinalIgnoreCase) == 0);
return (string.Equals(extension, CompositeFontExtension, StringComparison.OrdinalIgnoreCase));
}

internal static bool IsEnumerableFontUriScheme(Uri fontLocation)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ FontStretch fontStretch
{
if (faceNameBuilder.Length > 0)
{
faceNameBuilder.Append(" ");
faceNameBuilder.Append(' ');
}
faceNameBuilder.Append(parsedWeightName);
}
Expand All @@ -77,7 +77,7 @@ FontStretch fontStretch
{
if (faceNameBuilder.Length > 0)
{
faceNameBuilder.Append(" ");
faceNameBuilder.Append(' ');
}
faceNameBuilder.Append(parsedStyleName);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -417,8 +417,7 @@ private ByteRangeDownloader(Uri requestedUri, SafeWaitHandle eventHandle)
}

// Ensure uri is correct scheme (http or https) Do case-sensitive comparison since Uri.Scheme contract is to return in lower case only.
if (String.Compare(requestedUri.Scheme, Uri.UriSchemeHttp, StringComparison.Ordinal) != 0
&& String.Compare(requestedUri.Scheme, Uri.UriSchemeHttps, StringComparison.Ordinal) != 0)
if (!string.Equals(requestedUri.Scheme, Uri.UriSchemeHttp, StringComparison.Ordinal) && !string.Equals(requestedUri.Scheme, Uri.UriSchemeHttps, StringComparison.Ordinal))
{
throw new ArgumentException(SR.Get(SRID.InvalidScheme), "requestedUri");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ private static byte[] GetGuidByteArray(string guidString)
{
// Make sure we have at least on '-' since Guid constructor will take both dash'ed and non-dash'ed format of GUID string
// while XPS spec requires dash'ed format of GUID
if (guidString.IndexOf('-') == -1)
if (!guidString.Contains('-'))
{
throw new ArgumentException(SR.Get(SRID.InvalidPartName));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ internal NetStream(

// only attempt out-of-order requests on well-behaved HTTP servers
// (Note: MSDN indicates that uri.Scheme is always lower case)
if (fullStreamLength > 0 && ((String.Compare(uri.Scheme, Uri.UriSchemeHttp, StringComparison.Ordinal) == 0) ||
(String.Compare(uri.Scheme, Uri.UriSchemeHttps, StringComparison.Ordinal) == 0)))
if (fullStreamLength > 0 && ((string.Equals(uri.Scheme, Uri.UriSchemeHttp, StringComparison.Ordinal)) ||
(string.Equals(uri.Scheme, Uri.UriSchemeHttps, StringComparison.Ordinal))))
{
_allowByteRangeRequests = true;
_readEventHandles[(int)ReadEvent.ByteRangeReadEvent] = new AutoResetEvent(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ private Point[] FilterPoints(Point[] path)
// should be further tuned considering trade-off of performance and accuracy.
// In general, the larger the value, more points are filtered but less accurate.
// For a value of 0.5, typically 70% - 80% percent of the points are filtered out.
private static readonly double CollinearTolerance = 0.1f;
private const double CollinearTolerance = 0.1f;

#endregion
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ internal GestureRecognitionResult[] Recognize(StrokeCollection strokes)
}

// Create an empty result.
GestureRecognitionResult[] recResults = new GestureRecognitionResult[]{};
GestureRecognitionResult[] recResults = Array.Empty<GestureRecognitionResult>();

if ( strokes.Count == 0 )
{
Expand Down Expand Up @@ -617,7 +617,7 @@ private void ReleaseResourcesinPacketDescription(MS.Win32.Recognizer.PACKET_DESC
/// <returns></returns>
private GestureRecognitionResult[] InvokeGetAlternateList()
{
GestureRecognitionResult[] recResults = new GestureRecognitionResult[] { };
GestureRecognitionResult[] recResults = Array.Empty<GestureRecognitionResult>();
int hr = 0;

MS.Win32.Recognizer.RECO_RANGE recoRange;
Expand Down Expand Up @@ -681,7 +681,7 @@ private GestureRecognitionResult[] InvokeGetAlternateList()
/// <returns></returns>
private GestureRecognitionResult[] InvokeGetLatticePtr()
{
GestureRecognitionResult[] recResults = new GestureRecognitionResult[] { };
GestureRecognitionResult[] recResults = Array.Empty<GestureRecognitionResult>();

// int hr = 0;
IntPtr ptr = IntPtr.Zero;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -463,12 +463,12 @@ private LZCodec LZCodec
/// <summary>
/// Static members defined in Penimc code
/// </summary>
internal static readonly byte NoCompression = 0x00;
internal static readonly byte DefaultCompression = 0xC0;
internal static readonly byte IndexedHuffman = 0x80;
internal static readonly byte LempelZiv = 0x80;
internal static readonly byte DefaultBAACount = 8;
internal static readonly byte MaxBAACount = 10;
internal const byte NoCompression = 0x00;
internal const byte DefaultCompression = 0xC0;
internal const byte IndexedHuffman = 0x80;
internal const byte LempelZiv = 0x80;
internal const byte DefaultBAACount = 8;
internal const byte MaxBAACount = 10;


private static readonly double[] DefaultFirstSquareRoot = { 1, 1, 1, 4, 9, 16, 36, 49};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,11 @@ namespace MS.Internal.Ink.InkSerializedFormat
/// </summary>
internal static class DrawingAttributeSerializer
{
private static readonly double V1PenWidthWhenWidthIsMissing = 25.0f;
private static readonly double V1PenHeightWhenHeightIsMissing = 25.0f;
private static readonly int TransparencyDefaultV1 = 0;
internal static readonly uint RasterOperationMaskPen = 9;
internal static readonly uint RasterOperationDefaultV1 = 13;
private const double V1PenWidthWhenWidthIsMissing = 25.0f;
private const double V1PenHeightWhenHeightIsMissing = 25.0f;
private const int TransparencyDefaultV1 = 0;
internal const uint RasterOperationMaskPen = 9;
internal const uint RasterOperationDefaultV1 = 13;

/// <summary>The v1 ISF version of the pen tip shape. For v2, this is represented as StylusShape</summary>
private enum PenTip
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ internal void Decode(ref int data, ref int extra, BitStreamReader reader)
/// <summary>
/// Private statics
/// </summary>
private static readonly byte MaxBAASize = 10;
private const byte MaxBAASize = 10;

/// <summary>
/// Private helper class
Expand Down Expand Up @@ -334,8 +334,8 @@ internal byte GetBitsAtIndex(uint index)
/// <summary>
/// Private statics
/// </summary>
private static readonly byte MaxBAASize = 10;
private static readonly byte DefaultBAACount = 8;
private const byte MaxBAASize = 10;
private const byte DefaultBAACount = 8;
private static readonly byte[][] DefaultBAAData = new byte[][]
{
new byte[]{0, 1, 2, 4, 6, 8, 12, 16, 24, 32},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ namespace MS.Internal.Ink.InkSerializedFormat
internal class StrokeCollectionSerializer
{
#region Constants (Static Fields)
internal static readonly double AvalonToHimetricMultiplier = 2540.0d / 96.0d;
internal static readonly double HimetricToAvalonMultiplier = 96.0d / 2540.0d;
internal const double AvalonToHimetricMultiplier = 2540.0d / 96.0d;
internal const double HimetricToAvalonMultiplier = 96.0d / 2540.0d;
internal static readonly TransformDescriptor IdentityTransformDescriptor;

static StrokeCollectionSerializer()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ internal byte[] Uncompress(byte[] input, int inputIndex)
/// <summary>
/// Statics / constants
/// </summary>
private static readonly int FirstMaxMatchLength = 0x10;
private static readonly int RingBufferLength = 4069;
private static readonly int MaxLiteralLength = 2;
}
private const int FirstMaxMatchLength = 0x10;
private const int RingBufferLength = 4069;
private const int MaxLiteralLength = 2;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ protected virtual void AddPointImpl(Point point)
private List<Point> _points;
private Rect _bounds = Rect.Empty;
private bool _incrementalLassoDirty = false;
private static readonly double MinDistance = 1.0;
private const double MinDistance = 1.0;

#endregion

Expand Down
Loading

0 comments on commit abd651a

Please sign in to comment.