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

Commit

Permalink
Merge pull request #2868 from DamirAinullin/master
Browse files Browse the repository at this point in the history
Small perfomance improvments for Dictionary
  • Loading branch information
thecodejunkie authored May 6, 2018
2 parents 93c1594 + 5bafbc7 commit c2a5254
Show file tree
Hide file tree
Showing 30 changed files with 120 additions and 92 deletions.
5 changes: 2 additions & 3 deletions src/Nancy.Authentication.Forms/FormsAuthentication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -243,13 +243,12 @@ private static Action<NancyContext> GetRedirectToLoginHook(FormsAuthenticationCo
/// <returns>Returns user guid, or Guid.Empty if not present or invalid</returns>
private static Guid GetAuthenticatedUserFromCookie(NancyContext context, FormsAuthenticationConfiguration configuration)
{
if (!context.Request.Cookies.ContainsKey(formsAuthenticationCookieName))
string cookieValueEncrypted;
if (!context.Request.Cookies.TryGetValue(formsAuthenticationCookieName, out cookieValueEncrypted))
{
return Guid.Empty;
}

var cookieValueEncrypted = context.Request.Cookies[formsAuthenticationCookieName];

if (string.IsNullOrEmpty(cookieValueEncrypted))
{
return Guid.Empty;
Expand Down
8 changes: 4 additions & 4 deletions src/Nancy.Hosting.Aspnet/NancyHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,13 @@ private static long GetExpectedRequestLength(IDictionary<string, IEnumerable<str
return 0;
}

if (!incomingHeaders.ContainsKey("Content-Length"))
IEnumerable<string> values;
if (!incomingHeaders.TryGetValue("Content-Length", out values))
{
return 0;
}

var headerValue =
incomingHeaders["Content-Length"].SingleOrDefault();
var headerValue = values.SingleOrDefault();

if (headerValue == null)
{
Expand Down Expand Up @@ -180,4 +180,4 @@ private static void SetHttpResponseHeaders(HttpContextBase context, Response res
}
}
}
}
}
12 changes: 6 additions & 6 deletions src/Nancy.Hosting.Self/NancyHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
using System.Threading.Tasks;
using Nancy.Bootstrapper;
using Nancy.Extensions;
using Nancy.Helpers;
using Nancy.IO;
using System.Threading;

Expand Down Expand Up @@ -371,8 +370,9 @@ private static void OutputWithContentLength(Response nancyResponse, HttpListener
buffer = memoryStream.ToArray();
}

var contentLength = (nancyResponse.Headers.ContainsKey("Content-Length")) ?
Convert.ToInt64(nancyResponse.Headers["Content-Length"]) :
string value;
var contentLength = nancyResponse.Headers.TryGetValue("Content-Length", out value) ?
Convert.ToInt64(value) :
buffer.Length;

response.SendChunked = false;
Expand All @@ -395,13 +395,13 @@ private static long GetExpectedRequestLength(IDictionary<string, IEnumerable<str
return 0;
}

if (!incomingHeaders.ContainsKey("Content-Length"))
IEnumerable<string> values;
if (!incomingHeaders.TryGetValue("Content-Length", out values))
{
return 0;
}

var headerValue =
incomingHeaders["Content-Length"].SingleOrDefault();
var headerValue = values.SingleOrDefault();

if (headerValue == null)
{
Expand Down
5 changes: 3 additions & 2 deletions src/Nancy.Metadata.Modules/MetadataModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,10 @@ public Type MetadataType
/// <returns>An instance of <see cref="MetadataType"/> if one exists, otherwise null.</returns>
public object GetMetadata(RouteDescription description)
{
if (this.metadata.ContainsKey(description.Name))
Func<RouteDescription, TMetadata> func;
if (this.metadata.TryGetValue(description.Name, out func))
{
return this.metadata[description.Name].Invoke(description);
return func.Invoke(description);
}

return null;
Expand Down
5 changes: 3 additions & 2 deletions src/Nancy.Owin/AppBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,13 @@ public static IAppBuilder UseNancy(this IAppBuilder builder, Action<NancyOptions

private static void HookDisposal(IAppBuilder builder, NancyOptions nancyOptions)
{
if (!builder.Properties.ContainsKey(AppDisposingKey))
object value;
if (!builder.Properties.TryGetValue(AppDisposingKey, out value))
{
return;
}

var appDisposing = builder.Properties[AppDisposingKey] as CancellationToken?;
var appDisposing = value as CancellationToken?;

if (appDisposing.HasValue)
{
Expand Down
3 changes: 2 additions & 1 deletion src/Nancy.Testing/ConfigurableBootstrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2102,7 +2102,8 @@ public IEnumerable<INancyModule> GetAllModules(NancyContext context)
/// <returns>The <see cref="INancyModule"/> instance</returns>
public INancyModule GetModule(Type moduleType, NancyContext context)
{
return this.moduleInstances.ContainsKey(moduleType.FullName) ? this.moduleInstances[moduleType.FullName] : null;
INancyModule module;
return this.moduleInstances.TryGetValue(moduleType.FullName, out module) ? module : null;
}

/// <summary>
Expand Down
7 changes: 4 additions & 3 deletions src/Nancy.Testing/NancyContextExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ private static T Cache<T>(NancyContext context, string key, Func<T> getData)
// We only really want to generate this once, so we'll stick it in the context
// This isn't ideal, but we don't want to hide the guts of the context from the
// tests this will have to do.
if (context.Items.ContainsKey(key))
object value;
if (context.Items.TryGetValue(key, out value))
{
return (T)context.Items[key];
return (T)value;
}

T data = getData.Invoke();
Expand Down Expand Up @@ -85,4 +86,4 @@ public static TModel XmlBody<TModel>(this NancyContext context)
});
}
}
}
}
5 changes: 3 additions & 2 deletions src/Nancy.Testing/TestingViewBrowserResponseExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,13 @@ public static string GetModulePath(this BrowserResponse response)

private static string GetContextValue(BrowserResponse response, string key)
{
if (!response.Context.Items.ContainsKey(key))
object val;
if (!response.Context.Items.TryGetValue(key, out val))
{
return string.Empty;
}

var value = (string)response.Context.Items[key];
var value = (string)val;
return string.IsNullOrEmpty(value) ? string.Empty : value;
}
}
Expand Down
7 changes: 3 additions & 4 deletions src/Nancy.ViewEngines.Razor/CSharp/CSharpClrTypeResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ namespace Nancy.ViewEngines.Razor.CSharp
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Razor.Tokenizer.Symbols;

/// <summary>
Expand Down Expand Up @@ -83,8 +82,8 @@ protected override Type ResolvePrimitiveType(string typeName)
{"bool", typeof (bool)},
{"object", typeof (object)},
};

return (primitives.ContainsKey(typeName) ? primitives[typeName] : null);
Type type;
return primitives.TryGetValue(typeName, out type) ? type : null;
}
}
}
}
4 changes: 2 additions & 2 deletions src/Nancy/Diagnostics/DiagnosticsHook.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,12 +228,12 @@ private static DiagnosticsSession GetSession(NancyContext context, DiagnosticsCo
return ProcessLogin(context, diagnosticsConfiguration, serializer);
}

if (!context.Request.Cookies.ContainsKey(diagnosticsConfiguration.CookieName))
string encryptedValue;
if (!context.Request.Cookies.TryGetValue(diagnosticsConfiguration.CookieName, out encryptedValue))
{
return null;
}

var encryptedValue = context.Request.Cookies[diagnosticsConfiguration.CookieName];
var hmacStringLength = Base64Helpers.GetBase64Length(diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength);
var encryptedSession = encryptedValue.Substring(hmacStringLength);
var hmacString = encryptedValue.Substring(0, hmacStringLength);
Expand Down
10 changes: 6 additions & 4 deletions src/Nancy/Extensions/ModelValidationErrorExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@ public static class ModelValidationResultExtensions
/// <returns>A reference to the <see cref="ModelValidationResult.Errors"/> property.</returns>
public static IDictionary<string, IList<ModelValidationError>> Add(this IDictionary<string, IList<ModelValidationError>> errors, string name, string errorMessage)
{
if (!errors.ContainsKey(name))
IList<ModelValidationError> value;
if (!errors.TryGetValue(name, out value))
{
errors[name] = new List<ModelValidationError>();
value = new List<ModelValidationError>();
errors[name] = value;
}

errors[name].Add(new ModelValidationError(name, errorMessage));
value.Add(new ModelValidationError(name, errorMessage));

return errors;
}
}
}
}
5 changes: 3 additions & 2 deletions src/Nancy/Helpers/HttpEncoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -479,8 +479,9 @@ internal static string HtmlDecode(string s)
if (c == ';')
{
string key = entity.ToString();
if (key.Length > 1 && Entities.ContainsKey(key.Substring(1, key.Length - 2)))
key = Entities[key.Substring(1, key.Length - 2)].ToString();
char value;
if (key.Length > 1 && Entities.TryGetValue(key.Substring(1, key.Length - 2), out value))
key = value.ToString();

output.Append(key);
state = 0;
Expand Down
3 changes: 2 additions & 1 deletion src/Nancy/Json/Simple/SimpleJson.cs
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,8 @@ public void Clear()
/// </returns>
public bool Contains(KeyValuePair<string, object> item)
{
return this._members.ContainsKey(item.Key) && this._members[item.Key] == item.Value;
object value;
return this._members.TryGetValue(item.Key, out value) && value == item.Value;
}

/// <summary>
Expand Down
3 changes: 2 additions & 1 deletion src/Nancy/Json/SimpleJson.cs
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,8 @@ public void Clear()
/// </returns>
public bool Contains(KeyValuePair<string, object> item)
{
return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value;
object value;
return _members.TryGetValue(item.Key, out value) && value == item.Value;
}

/// <summary>
Expand Down
10 changes: 6 additions & 4 deletions src/Nancy/ModelBinding/DefaultBinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -475,14 +475,14 @@ private static string GetValue(string propertyName, BindingContext context, int
.Distinct()
.Select((k, i) => new KeyValuePair<int, int>(i, k))
.ToDictionary(k => k.Key, v => v.Value);

if (indexindexes.ContainsKey(index))
int indexValue;
if (indexindexes.TryGetValue(index, out indexValue))
{
var propertyValue =
context.RequestData.Where(c =>
{
var indexId = IsMatch(c.Key);
return c.Key.StartsWith(propertyName, StringComparison.OrdinalIgnoreCase) && indexId != -1 && indexId == indexindexes[index];
return c.Key.StartsWith(propertyName, StringComparison.OrdinalIgnoreCase) && indexId != -1 && indexId == indexValue;
})
.Select(k => k.Value)
.FirstOrDefault();
Expand All @@ -492,7 +492,9 @@ private static string GetValue(string propertyName, BindingContext context, int

return string.Empty;
}
return context.RequestData.ContainsKey(propertyName) ? context.RequestData[propertyName] : string.Empty;

string value;
return context.RequestData.TryGetValue(propertyName, out value) ? value : string.Empty;
}

private object DeserializeRequestBody(BindingContext context)
Expand Down
5 changes: 3 additions & 2 deletions src/Nancy/Owin/NancyMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,9 @@ private static Task RequestComplete(
if (nancyResponse.Cookies != null && nancyResponse.Cookies.Count != 0)
{
const string setCookieHeaderKey = "Set-Cookie";
string[] setCookieHeader = owinResponseHeaders.ContainsKey(setCookieHeaderKey)
? owinResponseHeaders[setCookieHeaderKey]
string[] cookieHeader;
string[] setCookieHeader = owinResponseHeaders.TryGetValue(setCookieHeaderKey, out cookieHeader)
? cookieHeader
: ArrayCache.Empty<string>();
owinResponseHeaders[setCookieHeaderKey] = setCookieHeader
.Concat(nancyResponse.Cookies.Select(cookie => cookie.ToString()))
Expand Down
6 changes: 3 additions & 3 deletions src/Nancy/RequestHeaders.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ namespace Nancy
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Nancy.Cookies;
using Nancy.Responses.Negotiation;

Expand Down Expand Up @@ -274,8 +273,9 @@ public IEnumerable<string> this[string name]
{
get
{
return (this.headers.ContainsKey(name)) ?
this.headers[name] :
IEnumerable<string> value;
return this.headers.TryGetValue(name, out value) ?
value :
Enumerable.Empty<string>();
}
}
Expand Down
7 changes: 5 additions & 2 deletions src/Nancy/Response.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ namespace Nancy
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Nancy.Cookies;
using Nancy.Helpers;
Expand Down Expand Up @@ -43,7 +42,11 @@ public Response()
/// <remarks>The default value is <c>text/html</c>.</remarks>
public string ContentType
{
get { return Headers.ContainsKey("content-type") ? Headers["content-type"] : this.contentType; }
get
{
string value;
return Headers.TryGetValue("content-type", out value) ? value : this.contentType;
}
set { this.contentType = value; }
}

Expand Down
6 changes: 3 additions & 3 deletions src/Nancy/Responses/Negotiation/DefaultResponseNegotiator.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
namespace Nancy.Responses.Negotiation
{
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -390,9 +389,10 @@ protected virtual string CreateLinkHeader(Url requestUrl, IEnumerable<KeyValuePa
/// <param name="response">The response.</param>
private static void AddContentTypeHeader(NegotiationContext negotiationContext, Response response)
{
if (negotiationContext.Headers.ContainsKey("Content-Type"))
string contentType;
if (negotiationContext.Headers.TryGetValue("Content-Type", out contentType))
{
response.ContentType = negotiationContext.Headers["Content-Type"];
response.ContentType = contentType;
negotiationContext.Headers.Remove("Content-Type");
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/Nancy/Responses/Negotiation/MediaRangeParameters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ public string this[string name]
{
get
{
return (this.parameters.ContainsKey(name)) ? this.parameters[name] : null;
string value;
return this.parameters.TryGetValue(name, out value) ? value : null;
}
}

Expand Down Expand Up @@ -126,4 +127,4 @@ public override string ToString()
return this;
}
}
}
}
10 changes: 6 additions & 4 deletions src/Nancy/Routing/DefaultRouteCacheProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,16 +79,18 @@ public IDictionary<string, IList<object>> GetAllRoutes()

foreach (var entry in this.cacheProvider.GetCache().Values.SelectMany(t => t.Select(t1 => t1.Item2)))
{
if (!result.ContainsKey(entry.Method))
IList<object> value;
if (!result.TryGetValue(entry.Method, out value))
{
result[entry.Method] = new List<object>();
value = new List<object>();
result[entry.Method] = value;
}

result[entry.Method].Add(new { Name = entry.Name, Path = entry.Path });
value.Add(new { Name = entry.Name, Path = entry.Path });
}

return result;
}
}
}
}
}
Loading

0 comments on commit c2a5254

Please sign in to comment.