Skip to content

Commit

Permalink
Avoid doing multiple dictionary lookups (get key hash, find bucket, i…
Browse files Browse the repository at this point in the history
…terate bucket) (#3580)

(cherry picked from commit 750b4ec)
  • Loading branch information
Henr1k80 authored and russcam committed Mar 6, 2019
1 parent f5625fa commit 641df53
Show file tree
Hide file tree
Showing 11 changed files with 70 additions and 71 deletions.
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
4 changes: 2 additions & 2 deletions src/Elasticsearch.Net/Transport/Sniff/SniffResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,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
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,39 +17,39 @@ 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("inline"))
metric.Script = properties["script"].ToObject<InlineScript>();
else if (scriptProps.ContainsKey("file"))
metric.Script = properties["script"].ToObject<FileScript>();
else if (scriptProps.ContainsKey("id"))
metric.Script = properties["id"].ToObject<IndexedScript>();
metric.Script = scriptToken.ToObject<InlineScript>();
else if (scriptProps.ContainsKey("file"))
metric.Script = scriptToken.ToObject<FileScript>();
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 @@ -200,9 +200,9 @@ public TConnectionSettings MapIdPropertyFor<TDocument>(Expression<Func<TDocument
var memberInfo = new MemberInfoResolver(objectPath);
var fieldName = memberInfo.Members.Single().Name;

if (_idProperties.ContainsKey(typeof(TDocument)))
if (_idProperties.TryGetValue(typeof(TDocument), out var idProperty))
{
if (_idProperties[typeof(TDocument)].Equals(fieldName))
if (idProperty.Equals(fieldName))
return (TConnectionSettings)this;

throw new ArgumentException(
Expand Down Expand Up @@ -245,10 +245,10 @@ private void ApplyPropertyMappings<TDocument>(IList<IClrTypePropertyMapping<TDoc
throw new ArgumentException($"Expression {e} does contain any member access");

var memberInfo = memberInfoResolver.Members.Last();
if (_propertyMappings.ContainsKey(memberInfo))
if (_propertyMappings.TryGetValue(memberInfo, out var 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
23 changes: 12 additions & 11 deletions src/Nest/CommonOptions/Scripting/ScriptJsonConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,32 +20,33 @@ 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("file"))
else if (dict.TryGetValue("file", out JToken fileToken))
{
var file = dict["file"].ToString();
var file = fileToken.ToString();
script = new FileScript(file);
}
if (dict.ContainsKey("id"))
else 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;
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotSupportedException();
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) =>
throw new NotSupportedException();
}
}
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 @@ -65,30 +65,30 @@ 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("file"))
else if (dict.TryGetValue("file", out JToken fileToken))
{
var file = dict["file"].ToString();
var file = fileToken.ToString();
#pragma warning disable 618
scriptCondition = new FileScriptCondition(file);
#pragma warning restore 618
}
if (dict.ContainsKey("id"))
else 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 class ChainInputDescriptor : DescriptorBase<ChainInputDescriptor, IChainI
/// <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
25 changes: 10 additions & 15 deletions src/Nest/XPack/Watcher/Transform/ScriptTransformBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,33 +64,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("source", out JToken sourceToken))
{
var inline = dict["inline"].ToString();
var inline = sourceToken.ToString();
scriptTransform = new InlineScriptTransform(inline);
}
else if (dict.ContainsKey("source"))
else if (dict.TryGetValue("file", out var fileToken))
{
var inline = dict["source"].ToString();
scriptTransform = new InlineScriptTransform(inline);
}
else if (dict.ContainsKey("file"))
{
var file = dict["file"].ToString();
var file = fileToken.ToString();
scriptTransform = new FileScriptTransform(file);
}
else if (dict.ContainsKey("id"))
else 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

0 comments on commit 641df53

Please sign in to comment.