Skip to content

Avoid doing multiple dictionary lookups #3580

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

Merged
merged 1 commit into from
Mar 6, 2019
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
4 changes: 2 additions & 2 deletions src/Elasticsearch.Net/Responses/Sniff/SniffResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ internal bool HttpEnabled
{
get
{
if (settings != null && settings.ContainsKey("http.enabled"))
return Convert.ToBoolean(settings["http.enabled"]);
if (settings != null && settings.TryGetValue("http.enabled", out object httpEnabled))
return Convert.ToBoolean(httpEnabled);

return http != null;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Elasticsearch.Net/Serialization/SimpleJson.cs
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ public void Clear()
/// </returns>
public bool Contains(KeyValuePair<string, object> item)
{
return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value;
return _members.TryGetValue(item.Key, out object value) && value == item.Value;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
var percentileRanks = new PercentileRanksAggregation();
ReadMetricProperties(percentileRanks, properties);
percentileRanks.Method = ReadMethodProperty(properties);
if (properties.ContainsKey("values"))
percentileRanks.Values = properties["values"].ToObject<List<double>>();
if (properties.TryGetValue("values", out JToken valuesToken))
percentileRanks.Values = valuesToken.ToObject<List<double>>();
return percentileRanks;

;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,37 +17,37 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
var percentiles = new PercentilesAggregation();
ReadMetricProperties(percentiles, properties);
percentiles.Method = ReadMethodProperty(properties);
if (properties.ContainsKey("percents"))
percentiles.Percents = properties["percents"].ToObject<List<double>>();
if (properties.TryGetValue("percents", out JToken percentsToken))
percentiles.Percents = percentsToken.ToObject<List<double>>();
return percentiles;
}

protected IPercentilesMethod ReadMethodProperty(Dictionary<string, JToken> properties)
{
IPercentilesMethod method = null;
if (properties.ContainsKey("hdr"))
method = properties["hdr"].ToObject<HDRHistogramMethod>();
else if (properties.ContainsKey("tdigest"))
method = properties["tdigest"].ToObject<TDigestMethod>();
if (properties.TryGetValue("hdr", out JToken hdrToken))
method = hdrToken.ToObject<HDRHistogramMethod>();
else if (properties.TryGetValue("tdigest", out JToken tdigestToken))
method = tdigestToken.ToObject<TDigestMethod>();
return method;
}

protected void ReadMetricProperties(IMetricAggregation metric, Dictionary<string, JToken> properties)
{
if (properties.ContainsKey("field"))
metric.Field = properties["field"].ToString();
if (properties.TryGetValue("field", out JToken fieldToken))
metric.Field = fieldToken.ToString();

if (properties.ContainsKey("script"))
if (properties.TryGetValue("script", out JToken scriptToken))
{
var scriptProps = JObject.FromObject(properties["script"]).Properties().ToDictionary(p => p.Name, p => p.Value);
var scriptProps = JObject.FromObject(scriptToken).Properties().ToDictionary(p => p.Name, p => p.Value);
if (scriptProps.ContainsKey("source") || scriptProps.ContainsKey("inline"))
metric.Script = properties["script"].ToObject<InlineScript>();
else if (scriptProps.ContainsKey("id"))
metric.Script = properties["id"].ToObject<IndexedScript>();
metric.Script = scriptToken.ToObject<InlineScript>();
else if (scriptProps.TryGetValue("id", out JToken idToken))
metric.Script = idToken.ToObject<IndexedScript>();
}

if (properties.ContainsKey("missing"))
metric.Missing = double.Parse(properties["missing"].ToString());
if (properties.TryGetValue("missing", out JToken missingToken))
metric.Missing = double.Parse(missingToken.ToString());
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s

private T GetOrDefault<T>(string key, Dictionary<string, JToken> properties)
{
if (!properties.ContainsKey(key)) return default(T);
if (!properties.TryGetValue(key, out JToken value)) return default(T);
#if DOTNETCORE
return properties[key].ToObject<T>();
return value.ToObject<T>();
#else
return (T)Convert.ChangeType(properties[key], typeof(T));
return (T)Convert.ChangeType(value, typeof(T));
#endif
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,9 @@ private void MapIdPropertyFor<TDocument>(Expression<Func<TDocument, object>> obj
var memberInfo = new MemberInfoResolver(objectPath);
var fieldName = memberInfo.Members.Single().Name;

if (_idProperties.ContainsKey(typeof(TDocument)))
if (_idProperties.TryGetValue(typeof(TDocument), out string idPropertyFieldName))
{
if (_idProperties[typeof(TDocument)].Equals(fieldName)) return;
if (idPropertyFieldName.Equals(fieldName)) return;

throw new ArgumentException(
$"Cannot map '{fieldName}' as the id property for type '{typeof(TDocument).Name}': it already has '{_idProperties[typeof(TDocument)]}' mapped.");
Expand All @@ -191,9 +191,9 @@ private void MapRoutePropertyFor<TDocument>(Expression<Func<TDocument, object>>
var memberInfo = new MemberInfoResolver(objectPath);
var fieldName = memberInfo.Members.Single().Name;

if (_routeProperties.ContainsKey(typeof(TDocument)))
if (_routeProperties.TryGetValue(typeof(TDocument), out string routePropertyFieldName))
{
if (_routeProperties[typeof(TDocument)].Equals(fieldName)) return;
if (routePropertyFieldName.Equals(fieldName)) return;

throw new ArgumentException(
$"Cannot map '{fieldName}' as the route property for type '{typeof(TDocument).Name}': it already has '{_routeProperties[typeof(TDocument)]}' mapped.");
Expand All @@ -216,10 +216,10 @@ private void ApplyPropertyMappings<TDocument>(IList<IClrPropertyMapping<TDocumen
throw new ArgumentException($"Expression {e} does contain any member access");

var memberInfo = memberInfoResolver.Members.Last();
if (_propertyMappings.ContainsKey(memberInfo))
if (_propertyMappings.TryGetValue(memberInfo, out IPropertyMapping propertyMapping))
{
var newName = mapping.NewName;
var mappedAs = _propertyMappings[memberInfo].Name;
var mappedAs = propertyMapping.Name;
var typeName = typeof(TDocument).Name;
if (mappedAs.IsNullOrEmpty() && newName.IsNullOrEmpty())
throw new ArgumentException($"Property mapping '{e}' on type is already ignored");
Expand Down
20 changes: 10 additions & 10 deletions src/Nest/CommonOptions/Scripting/ScriptJsonConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,28 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
if (!dict.HasAny()) return null;

IScript script = null;
if (dict.ContainsKey("inline"))
if (dict.TryGetValue("inline", out JToken inlineToken))
{
var inline = dict["inline"].ToString();
var inline = inlineToken.ToString();
script = new InlineScript(inline);
}
if (dict.ContainsKey("source"))
if (dict.TryGetValue("source", out JToken sourceToken))
{
var inline = dict["source"].ToString();
var inline = sourceToken.ToString();
script = new InlineScript(inline);
}
if (dict.ContainsKey("id"))
if (dict.TryGetValue("id", out JToken idToken))
{
var id = dict["id"].ToString();
var id = idToken.ToString();
script = new IndexedScript(id);
}

if (script == null) return null;

if (dict.ContainsKey("lang"))
script.Lang = dict["lang"].ToString();
if (dict.ContainsKey("params"))
script.Params = dict["params"].ToObject<Dictionary<string, object>>();
if (dict.TryGetValue("lang", out JToken langToken))
script.Lang = langToken.ToString();
if (dict.TryGetValue("params", out JToken paramsToken))
script.Params = paramsToken.ToObject<Dictionary<string, object>>();

return script;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,9 +256,8 @@ private static void Set<T>(IIndexSettings s, IDictionary<string, JProperty> sett
JsonSerializer serializer = null
)
{
if (!settings.ContainsKey(key)) return;
if (!settings.TryGetValue(key, out JProperty v)) return;

var v = settings[key];
var value = serializer == null ? v.Value.ToObject<T>() : v.Value.ToObject<T>(serializer);
assign(value);
s.Add(key, value);
Expand All @@ -269,9 +268,8 @@ private static void SetArray<TArray, TItem>(IIndexSettings s, IDictionary<string
Action<TItem> assign2, JsonSerializer serializer = null
)
{
if (!settings.ContainsKey(key)) return;
if (!settings.TryGetValue(key, out JProperty v)) return;

var v = settings[key];
if (v.Value is JArray)
{
var value = serializer == null ? v.Value.ToObject<TArray>() : v.Value.ToObject<TArray>(serializer);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ private TRepository Get<TRepository>(string name)
where TRepository : class, ISnapshotRepository
{
if (Repositories == null) return null;
if (!Repositories.ContainsKey(name)) return null;
if (!Repositories.TryGetValue(name, out ISnapshotRepository repository)) return null;

return Repositories[name] as TRepository;
return repository as TRepository;
}
}
}
20 changes: 10 additions & 10 deletions src/Nest/XPack/Watcher/Condition/ScriptConditionBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,28 +68,28 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
if (!dict.HasAny()) return null;

IScriptCondition scriptCondition = null;
if (dict.ContainsKey("inline"))
if (dict.TryGetValue("inline", out JToken inlineToken))
{
var inline = dict["inline"].ToString();
var inline = inlineToken.ToString();
scriptCondition = new InlineScriptCondition(inline);
}
if (dict.ContainsKey("source"))
if (dict.TryGetValue("source", out JToken sourceToken))
{
var inline = dict["source"].ToString();
var inline = sourceToken.ToString();
scriptCondition = new InlineScriptCondition(inline);
}
if (dict.ContainsKey("id"))
if (dict.TryGetValue("id", out JToken idToken))
{
var id = dict["id"].ToString();
var id = idToken.ToString();
scriptCondition = new IndexedScriptCondition(id);
}

if (scriptCondition == null) return null;

if (dict.ContainsKey("lang"))
scriptCondition.Lang = dict["lang"].ToString();
if (dict.ContainsKey("params"))
scriptCondition.Params = dict["params"].ToObject<Dictionary<string, object>>();
if (dict.TryGetValue("lang", out JToken langToken))
scriptCondition.Lang = langToken.ToString();
if (dict.TryGetValue("params", out JToken paramsToken))
scriptCondition.Params = paramsToken.ToObject<Dictionary<string, object>>();

return scriptCondition;
}
Expand Down
11 changes: 7 additions & 4 deletions src/Nest/XPack/Watcher/Input/ChainInput.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,13 @@ public ChainInputDescriptor() { }
/// <inheritdoc />
public ChainInputDescriptor Input(string name, Func<InputDescriptor, InputContainer> selector)
{
if (Self.Inputs == null) Self.Inputs = new Dictionary<string, InputContainer>();

if (Self.Inputs.ContainsKey(name))
throw new InvalidOperationException($"An input named '{name}' has already been specified. Choose a different name");
if (Self.Inputs != null)
{
if (Self.Inputs.ContainsKey(name))
throw new InvalidOperationException($"An input named '{name}' has already been specified. Choose a different name");
}
else
Self.Inputs = new Dictionary<string, InputContainer>();

Self.Inputs.Add(name, selector.InvokeOrDefault(new InputDescriptor()));
return this;
Expand Down
20 changes: 10 additions & 10 deletions src/Nest/XPack/Watcher/Transform/ScriptTransformBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,28 +67,28 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
if (!dict.HasAny()) return null;

IScriptTransform scriptTransform = null;
if (dict.ContainsKey("inline"))
if (dict.TryGetValue("inline", out JToken inlineToken))
{
var inline = dict["inline"].ToString();
var inline = inlineToken.ToString();
scriptTransform = new InlineScriptTransform(inline);
}
if (dict.ContainsKey("source"))
if (dict.TryGetValue("source", out JToken sourceToken))
{
var inline = dict["source"].ToString();
var inline = sourceToken.ToString();
scriptTransform = new InlineScriptTransform(inline);
}
if (dict.ContainsKey("id"))
if (dict.TryGetValue("id", out JToken idToken))
{
var id = dict["id"].ToString();
var id = idToken.ToString();
scriptTransform = new IndexedScriptTransform(id);
}

if (scriptTransform == null) return null;

if (dict.ContainsKey("lang"))
scriptTransform.Lang = dict["lang"].ToString();
if (dict.ContainsKey("params"))
scriptTransform.Params = dict["params"].ToObject<Dictionary<string, object>>();
if (dict.TryGetValue("lang", out JToken langToken))
scriptTransform.Lang = langToken.ToString();
if (dict.TryGetValue("params", out JToken paramsToken))
scriptTransform.Params = paramsToken.ToObject<Dictionary<string, object>>();

return scriptTransform;
}
Expand Down