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

Clean up some MVC code #31511

Merged
2 commits merged into from
Apr 3, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -4,7 +4,9 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Microsoft.AspNetCore.Mvc.Controllers
Expand Down Expand Up @@ -55,6 +57,9 @@ internal static class ControllerBinderDelegateProvider
return null;
}

var parameters = actionDescriptor.Parameters as List<ParameterDescriptor> ?? actionDescriptor.Parameters.ToList();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we make these Arrays instead of lists?

var properties = actionDescriptor.BoundProperties as List<ParameterDescriptor> ?? actionDescriptor.BoundProperties.ToList();

return Bind;

async Task Bind(ControllerContext controllerContext, object controller, Dictionary<string, object?> arguments)
Expand All @@ -67,9 +72,8 @@ async Task Bind(ControllerContext controllerContext, object controller, Dictiona

Debug.Assert(valueProvider is not null);

var parameters = actionDescriptor.Parameters;

for (var i = 0; i < parameters.Count; i++)
var parameterCount = parameters.Count;
for (var i = 0; i < parameterCount; i++)
{
var parameter = parameters[i];
var bindingInfo = parameterBindingInfo![i];
Expand All @@ -95,8 +99,8 @@ async Task Bind(ControllerContext controllerContext, object controller, Dictiona
}
}

var properties = actionDescriptor.BoundProperties;
for (var i = 0; i < properties.Count; i++)
var propertyCount = properties.Count;
for (var i = 0; i < propertyCount; i++)
{
var property = properties[i];
var bindingInfo = propertyBindingInfo![i];
Expand Down
10 changes: 1 addition & 9 deletions src/Mvc/Mvc.Razor/src/TagHelpers/UrlResolutionTagHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -343,15 +343,7 @@ private static string CreateTrimmedString(string input, int start)

private static bool IsCharWhitespace(char ch)
{
for (var i = 0; i < ValidAttributeWhitespaceChars.Length; i++)
{
if (ValidAttributeWhitespaceChars[i] == ch)
{
return true;
}
}
// the character is not white space
return false;
return ValidAttributeWhitespaceChars.AsSpan().IndexOf(ch) != -1;
}

private class EncodeFirstSegmentContent : IHtmlContent
Expand Down
7 changes: 2 additions & 5 deletions src/Mvc/Mvc.TagHelpers/src/AttributeMatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace Microsoft.AspNetCore.Mvc.TagHelpers
Expand All @@ -24,7 +23,7 @@ internal static class AttributeMatcher
/// <returns><c>true</c> if a mode was determined, otherwise <c>false</c>.</returns>
public static bool TryDetermineMode<TMode>(
TagHelperContext context,
IReadOnlyList<ModeAttributes<TMode>> modeInfos,
ModeAttributes<TMode>[] modeInfos,
Func<TMode, TMode, int> compare,
out TMode result)
{
Expand All @@ -47,13 +46,11 @@ public static bool TryDetermineMode<TMode>(
result = default;

// Perf: Avoid allocating enumerator
var modeInfosCount = modeInfos.Count;
var allAttributes = context.AllAttributes;
// Read interface .Count once rather than per iteration
var allAttributesCount = allAttributes.Count;
for (var i = 0; i < modeInfosCount; i++)
foreach (var modeInfo in modeInfos.AsSpan())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need the AsSpan, foreaching over an array is pretty efficient.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interestingly, foreaching over and array and an explicit for loop over an array are equivalent.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interestingly, foreaching over and array and an explicit for loop over an array are equivalent.

C# compiler lowers the foreach over array to a for-loop (I believe this is done since the beginning).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, you can see it in the C# -> C# translation.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does the same for Span<T> too

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So:

  • T[] - foreach or for
  • Span<T> - foreach and for
  • List - CollectionsMarshal.AsSpan

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the T[] case for really (safe) high-perf for has the advantage that one can index with uints, so no movsxd (sign extensions) needs to be emitted. Unfortunately current JIT (at least the one from sharplab) got "de-optimized", this is tracked in dotnet/runtime#35618 now.

{
var modeInfo = modeInfos[i];
var requiredAttributes = modeInfo.Attributes;
// If there are fewer attributes present than required, one or more of them must be missing.
if (allAttributesCount >= requiredAttributes.Length &&
Expand Down
2 changes: 1 addition & 1 deletion src/Mvc/Mvc.ViewFeatures/src/DefaultDisplayTemplates.cs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ public static IHtmlContent ObjectTemplate(IHtmlHelper htmlHelper)
var viewBufferScope = serviceProvider.GetRequiredService<IViewBufferScope>();

var content = new HtmlContentBuilder(modelExplorer.Metadata.Properties.Count);
foreach (var propertyExplorer in modelExplorer.Properties)
foreach (var propertyExplorer in modelExplorer.PropertiesInternal.AsSpan())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here.

{
var propertyMetadata = propertyExplorer.Metadata;
if (!ShouldShow(propertyExplorer, templateInfo))
Expand Down
12 changes: 10 additions & 2 deletions src/Mvc/Mvc.ViewFeatures/src/DefaultEditorTemplates.cs
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ public static IHtmlContent ObjectTemplate(IHtmlHelper htmlHelper)
var viewBufferScope = serviceProvider.GetRequiredService<IViewBufferScope>();

var content = new HtmlContentBuilder(modelExplorer.Metadata.Properties.Count);
foreach (var propertyExplorer in modelExplorer.Properties)
foreach (var propertyExplorer in modelExplorer.PropertiesInternal.AsSpan())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same

{
var propertyMetadata = propertyExplorer.Metadata;
if (!ShouldShow(propertyExplorer, templateInfo))
Expand Down Expand Up @@ -482,6 +482,14 @@ public override void Write(char[] buffer, int index, int count)
}
}

public override void Write(ReadOnlySpan<char> buffer)
{
if (!buffer.IsEmpty)
{
HasContent = true;
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (!buffer.IsEmpty)
{
HasContent = true;
}
HasContent |= !buffer.IsEmpty;

?

}

public override void Write(string value)
{
if (!string.IsNullOrEmpty(value))
Expand Down Expand Up @@ -540,7 +548,7 @@ public override void Encode(TextWriter output, string value, int startIndex, int
return;
}

output.Write(value.Substring(startIndex, characterCount));
output.Write(value.AsSpan(startIndex, characterCount));
}

public override unsafe int FindFirstCharacterToEncode(char* text, int textLength)
Expand Down
4 changes: 2 additions & 2 deletions src/Mvc/Mvc.ViewFeatures/src/ModelExplorer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ public Type ModelType
/// </remarks>
public IEnumerable<ModelExplorer> Properties => PropertiesInternal;

private ModelExplorer[] PropertiesInternal
internal ModelExplorer[] PropertiesInternal
{
get
{
Expand Down Expand Up @@ -472,4 +472,4 @@ private ModelExplorer CreateExplorerForProperty(
return new ModelExplorer(_metadataProvider, this, propertyMetadata, modelAccessor);
}
}
}
}
8 changes: 4 additions & 4 deletions src/Mvc/Mvc.ViewFeatures/src/ModelExplorerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;

namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
Expand Down Expand Up @@ -68,12 +67,13 @@ public static string GetSimpleDisplayText(this ModelExplorer modelExplorer)
return stringResult;
}

var firstProperty = modelExplorer.Properties.FirstOrDefault();
if (firstProperty == null)
if (modelExplorer.PropertiesInternal.Length == 0)
{
return string.Empty;
}

var firstProperty = modelExplorer.PropertiesInternal[0];

if (firstProperty.Model == null)
{
return firstProperty.Metadata.NullDisplayText;
Expand All @@ -82,4 +82,4 @@ public static string GetSimpleDisplayText(this ModelExplorer modelExplorer)
return Convert.ToString(firstProperty.Model, CultureInfo.CurrentCulture);
}
}
}
}
2 changes: 1 addition & 1 deletion src/Mvc/MvcNoDeps.slnf
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
"src\\Mvc\\test\\WebSites\\SimpleWebSite\\SimpleWebSite.csproj",
"src\\Mvc\\test\\WebSites\\TagHelpersWebSite\\TagHelpersWebSite.csproj",
"src\\Mvc\\test\\WebSites\\VersioningWebSite\\VersioningWebSite.csproj",
"src\\Mvc\\test\\WebSites\\XmlFormattersWebSite\\XmlFormattersWebSite.csproj",
"src\\Mvc\\test\\WebSites\\XmlFormattersWebSite\\XmlFormattersWebSite.csproj"
]
}
}
4 changes: 1 addition & 3 deletions src/Shared/ChunkingCookieManager/ChunkingCookieManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,7 @@ private static int ParseChunksCount(string? value)
{
if (value != null && value.StartsWith(ChunkCountPrefix, StringComparison.Ordinal))
{
var chunksCountString = value.Substring(ChunkCountPrefix.Length);
int chunksCount;
if (int.TryParse(chunksCountString, NumberStyles.None, CultureInfo.InvariantCulture, out chunksCount))
if (int.TryParse(value.AsSpan(ChunkCountPrefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out var chunksCount))
{
return chunksCount;
}
Expand Down