Skip to content

Commit

Permalink
Reduce memory use by reducing array allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
nzdev committed Oct 15, 2020
1 parent 74513ba commit faf6b60
Show file tree
Hide file tree
Showing 20 changed files with 56 additions and 33 deletions.
2 changes: 1 addition & 1 deletion src/Umbraco.Core/Composing/TypeFinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ private static IEnumerable<Assembly> GetFilteredAssemblies(
if (excludeFromResults == null)
excludeFromResults = new HashSet<Assembly>();
if (exclusionFilter == null)
exclusionFilter = new string[] { };
exclusionFilter = Array.Empty<string>();

return GetAllAssemblies()
.Where(x => excludeFromResults.Contains(x) == false
Expand Down
21 changes: 21 additions & 0 deletions src/Umbraco.Core/Constants-StringArrays.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Umbraco.Core
{
public static partial class Constants
{

public static class StringArrays
{

/// <summary>
/// String array containing "value"
/// </summary>
public static readonly string[] ValueLower = Constants.StringArrays.ValueLower;
}
}
}
3 changes: 1 addition & 2 deletions src/Umbraco.Core/Logging/Serilog/SerilogLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,7 @@ private static void DumpThreadAborts(global::Serilog.ILogger logger, LogEventLev
messageTemplate += "\r\nFailed to create a minidump";

//Log a new entry (as opposed to appending to same log entry)
logger.Write(level, ex, "Failed to create a minidump ({ExType}: {ExMessage})",
new object[]{ ex.GetType().FullName, ex.Message });
logger.Write(level, ex, "Failed to create a minidump ({ExType}: {ExMessage})", ex.GetType().FullName, ex.Message);
}
}
}
Expand Down
6 changes: 6 additions & 0 deletions src/Umbraco.Core/Models/CultureImpact.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ private CultureImpact(string culture, bool isDefault = false)
/// </summary>
public static CultureImpact Invariant { get; } = new CultureImpact(null);


/// <summary>
/// Gets the impact of the invariant culture as an array.
/// </summary>
public static CultureImpact[] InvariantArray { get; } = new[] { new CultureImpact(null) };

/// <summary>
/// Creates an impact instance representing the impact of a specific culture.
/// </summary>
Expand Down
8 changes: 4 additions & 4 deletions src/Umbraco.Core/Models/Membership/User.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public User()
_language = Current.Configs.Global().DefaultUILanguage; // TODO: inject
_isApproved = true;
_isLockedOut = false;
_startContentIds = new int[] { };
_startMediaIds = new int[] { };
_startContentIds = Array.Empty<int>();
_startMediaIds = Array.Empty<int>();
//cannot be null
_rawPasswordValue = "";
}
Expand All @@ -52,8 +52,8 @@ public User(string name, string email, string username, string rawPasswordValue)
_userGroups = new HashSet<IReadOnlyUserGroup>();
_isApproved = true;
_isLockedOut = false;
_startContentIds = new int[] { };
_startMediaIds = new int[] { };
_startContentIds = Array.Empty<int>();
_startMediaIds = Array.Empty<int>();
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,9 @@ private void AddChildren(ITemplate[] all, List<ITemplate> descendants, string ma
}
}

private static readonly string[] _validTemplateDirs = new[] { SystemDirectories.MvcViews };
private static readonly IEnumerable<string> _validTemplateFileExtensions = new[] { "cshtml", "vbhtml" };

/// <summary>
/// Validates a <see cref="ITemplate"/>
/// </summary>
Expand All @@ -582,17 +585,9 @@ public bool ValidateTemplate(ITemplate template)
// are we using Path for something else?!
var path = template.VirtualPath;

// get valid paths
var validDirs = new[] { SystemDirectories.MvcViews };

// get valid extensions
var validExts = new List<string>();
validExts.Add("cshtml");
validExts.Add("vbhtml");

// validate path and extension
var validFile = IOHelper.VerifyEditPath(path, validDirs);
var validExtension = IOHelper.VerifyFileExtension(path, validExts);
var validFile = IOHelper.VerifyEditPath(path, _validTemplateDirs);
var validExtension = IOHelper.VerifyFileExtension(path, _validTemplateFileExtensions);
return validFile && validExtension;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public IEnumerable<ValidationResult> Validate(object value, string valueType, ob

var result = value.TryConvertTo<decimal>();
if (result.Success == false)
yield return new ValidationResult("The value " + value + " is not a valid decimal", new[] { "value" });
yield return new ValidationResult("The value " + value + " is not a valid decimal", Constants.StringArrays.ValueLower);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public IEnumerable<ValidationResult> Validate(object value, string valueType, ob
if (asString != string.Empty && emailVal.IsValid(asString) == false)
{
// TODO: localize these!
yield return new ValidationResult("Email is invalid", new[] { "value" });
yield return new ValidationResult("Email is invalid", Constants.StringArrays.ValueLower);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public IEnumerable<ValidationResult> Validate(object value, string valueType, ob
var result = value.TryConvertTo<int>();
if (result.Success == false)
{
yield return new ValidationResult("The value " + value + " is not a valid integer", new[] { "value" });
yield return new ValidationResult("The value " + value + " is not a valid integer", Constants.StringArrays.ValueLower);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public IEnumerable<ValidationResult> ValidateFormat(object value, string valueTy
if (string.IsNullOrWhiteSpace(format)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(format));
if (value == null || !new Regex(format).IsMatch(value.ToString()))
{
yield return new ValidationResult(_textService.Localize("validation", "invalidPattern"), new[] { "value" });
yield return new ValidationResult(_textService.Localize("validation", "invalidPattern"), Constants.StringArrays.ValueLower);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,23 +35,23 @@ public IEnumerable<ValidationResult> ValidateRequired(object value, string value
{
if (value == null)
{
yield return new ValidationResult(_textService.Localize("validation", "invalidNull"), new[] { "value" });
yield return new ValidationResult(_textService.Localize("validation", "invalidNull"), Constants.StringArrays.ValueLower);
yield break;
}

if (valueType.InvariantEquals(ValueTypes.Json))
{
if (value.ToString().DetectIsEmptyJson())
{
yield return new ValidationResult(_textService.Localize("validation", "invalidEmpty"), new[] { "value" });
yield return new ValidationResult(_textService.Localize("validation", "invalidEmpty"), Constants.StringArrays.ValueLower);
}

yield break;
}

if (value.ToString().IsNullOrWhiteSpace())
{
yield return new ValidationResult(_textService.Localize("validation", "invalidEmpty"), new[] { "value" });
yield return new ValidationResult(_textService.Localize("validation", "invalidEmpty"), Constants.StringArrays.ValueLower);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Umbraco.Core/Services/ContentTypeServiceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ internal static ContentTypeAvailableCompositionsResults GetAvailableCompositeCon

private static IContentTypeComposition[] GetAncestors(IContentTypeComposition ctype, IContentTypeComposition[] allContentTypes)
{
if (ctype == null) return new IContentTypeComposition[] {};
if (ctype == null) return Array.Empty<IContentTypeComposition>();
var ancestors = new List<IContentTypeComposition>();
var parentId = ctype.ParentId;
while (parentId > 0)
Expand Down
2 changes: 1 addition & 1 deletion src/Umbraco.Core/Services/Implement/ContentService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2647,7 +2647,7 @@ private PublishResult StrategyCanPublish(IScope scope, IContent content, bool ch
var variesByCulture = content.ContentType.VariesByCulture();

var impactsToPublish = culturesPublishing == null
? new[] { CultureImpact.Invariant } //if it's null it's invariant
? CultureImpact.InvariantArray //if it's null it's invariant
: culturesPublishing.Select(x => CultureImpact.Explicit(x, allLangs.Any(lang => lang.IsoCode.InvariantEquals(x) && lang.IsMandatory))).ToArray();

// publish the culture(s)
Expand Down
2 changes: 1 addition & 1 deletion src/Umbraco.Core/Services/UserServiceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public static EntityPermissionSet GetPermissionsForPath(this IUserService servic
/// <param name="entityIds"></param>
public static void RemoveUserGroupPermissions(this IUserService userService, int groupId, params int[] entityIds)
{
userService.ReplaceUserGroupPermissions(groupId, new char[] {}, entityIds);
userService.ReplaceUserGroupPermissions(groupId, Array.Empty<char>(), entityIds);
}

/// <summary>
Expand Down
1 change: 1 addition & 0 deletions src/Umbraco.Core/Umbraco.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@
<Compile Include="AssemblyExtensions.cs" />
<Compile Include="Constants-CharArrays.cs" />
<Compile Include="Constants-SqlTemplates.cs" />
<Compile Include="Constants-StringArrays.cs" />
<Compile Include="Migrations\Upgrade\V_8_0_0\Models\ContentTypeDto80.cs" />
<Compile Include="Migrations\Upgrade\V_8_0_0\Models\PropertyDataDto80.cs" />
<Compile Include="Migrations\Upgrade\V_8_0_0\Models\PropertyTypeDto80.cs" />
Expand Down
2 changes: 1 addition & 1 deletion src/Umbraco.Core/UriExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ internal static bool IsDefaultBackOfficeRequest(this Uri url, IGlobalSettings gl
return false;
}

private static string[] toInclude = new[] { ".aspx", ".ashx", ".asmx", ".axd", ".svc" };
/// <summary>
/// This is a performance tweak to check if this not an ASP.Net server file
/// .Net will pass these requests through to the module when in integrated mode.
Expand All @@ -149,7 +150,6 @@ internal static bool IsClientSideRequest(this Uri url)
{
var ext = Path.GetExtension(url.LocalPath);
if (ext.IsNullOrWhiteSpace()) return false;
var toInclude = new[] {".aspx", ".ashx", ".asmx", ".axd", ".svc"};
return toInclude.Any(ext.InvariantEquals) == false;
}
catch (ArgumentException)
Expand Down
2 changes: 1 addition & 1 deletion src/Umbraco.Core/Xml/XPath/MacroNavigator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ private class MacroRoot
{
public MacroRoot(IEnumerable<MacroParameter> parameters)
{
Parameters = parameters == null ? new MacroParameter[] {} : parameters.ToArray();
Parameters = parameters == null ? Array.Empty<MacroParameter>() : parameters.ToArray();
}

public MacroParameter[] Parameters { get; private set; }
Expand Down
2 changes: 1 addition & 1 deletion src/Umbraco.Web/Editors/BackOfficeServerVariables.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ internal Dictionary<string, object> BareMinimumServerVariables()
{"umbracoUrls", new[] {"authenticationApiBaseUrl", "serverVarsJs", "externalLoginsUrl", "currentUserApiBaseUrl", "iconApiBaseUrl"}},
{"umbracoSettings", new[] {"allowPasswordReset", "imageFileTypes", "maxFileSize", "loginBackgroundImage", "canSendRequiredEmail", "usernameIsEmail"}},
{"application", new[] {"applicationPath", "cacheBuster"}},
{"isDebuggingEnabled", new string[] { }},
{"isDebuggingEnabled", Array.Empty<string>()},
{"features", new [] {"disabledFeatures"}}
};
//now do the filtering...
Expand Down
4 changes: 2 additions & 2 deletions src/Umbraco.Web/Mvc/RenderViewEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,14 @@ public override ViewEngineResult FindView(ControllerContext controllerContext, s
{
return ShouldFindView(controllerContext, false)
? base.FindView(controllerContext, viewName, masterName, useCache)
: new ViewEngineResult(new string[] { });
: new ViewEngineResult(Array.Empty<string>());
}

public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
{
return ShouldFindView(controllerContext, true)
? base.FindPartialView(controllerContext, partialViewName, useCache)
: new ViewEngineResult(new string[] { });
: new ViewEngineResult(Array.Empty<string>());
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@ namespace Umbraco.Web.PropertyEditors
/// </summary>
public class DateTimeConfigurationEditor : ConfigurationEditor<DateTimeConfiguration>
{
private static readonly string[] _timeChars = new string[] { "H", "m", "s" };
public override IDictionary<string, object> ToValueEditor(object configuration)
{
var d = base.ToValueEditor(configuration);

var format = d["format"].ToString();

d["pickTime"] = format.ContainsAny(new string[] { "H", "m", "s" });
d["pickTime"] = format.ContainsAny(_timeChars);

return d;
}
Expand Down

0 comments on commit faf6b60

Please sign in to comment.