Skip to content

Commit 641df53

Browse files
Henr1k80russcam
authored andcommitted
Avoid doing multiple dictionary lookups (get key hash, find bucket, iterate bucket) (#3580)
(cherry picked from commit 750b4ec)
1 parent f5625fa commit 641df53

File tree

11 files changed

+70
-71
lines changed

11 files changed

+70
-71
lines changed

src/Elasticsearch.Net/Serialization/SimpleJson.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ public void Clear()
267267
/// </returns>
268268
public bool Contains(KeyValuePair<string, object> item)
269269
{
270-
return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value;
270+
return _members.TryGetValue(item.Key, out object value) && value == item.Value;
271271
}
272272

273273
/// <summary>

src/Elasticsearch.Net/Transport/Sniff/SniffResponse.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,8 @@ internal bool HttpEnabled
7979
{
8080
get
8181
{
82-
if (settings != null && settings.ContainsKey("http.enabled"))
83-
return Convert.ToBoolean(settings["http.enabled"]);
82+
if (settings != null && settings.TryGetValue("http.enabled", out object httpEnabled))
83+
return Convert.ToBoolean(httpEnabled);
8484

8585
return http != null;
8686
}

src/Nest/Aggregations/Metric/PercentileRanks/PercentileRanksAggregationJsonConverter.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
1717
var percentileRanks = new PercentileRanksAggregation();
1818
ReadMetricProperties(percentileRanks, properties);
1919
percentileRanks.Method = ReadMethodProperty(properties);
20-
if (properties.ContainsKey("values"))
21-
percentileRanks.Values = properties["values"].ToObject<List<double>>();
20+
if (properties.TryGetValue("values", out JToken valuesToken))
21+
percentileRanks.Values = valuesToken.ToObject<List<double>>();
2222
return percentileRanks;
2323

2424
;

src/Nest/Aggregations/Metric/Percentiles/PercentilesAggregationJsonConverter.cs

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,39 +17,39 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
1717
var percentiles = new PercentilesAggregation();
1818
ReadMetricProperties(percentiles, properties);
1919
percentiles.Method = ReadMethodProperty(properties);
20-
if (properties.ContainsKey("percents"))
21-
percentiles.Percents = properties["percents"].ToObject<List<double>>();
20+
if (properties.TryGetValue("percents", out JToken percentsToken))
21+
percentiles.Percents = percentsToken.ToObject<List<double>>();
2222
return percentiles;
2323
}
2424

2525
protected IPercentilesMethod ReadMethodProperty(Dictionary<string, JToken> properties)
2626
{
2727
IPercentilesMethod method = null;
28-
if (properties.ContainsKey("hdr"))
29-
method = properties["hdr"].ToObject<HDRHistogramMethod>();
30-
else if (properties.ContainsKey("tdigest"))
31-
method = properties["tdigest"].ToObject<TDigestMethod>();
28+
if (properties.TryGetValue("hdr", out JToken hdrToken))
29+
method = hdrToken.ToObject<HDRHistogramMethod>();
30+
else if (properties.TryGetValue("tdigest", out JToken tdigestToken))
31+
method = tdigestToken.ToObject<TDigestMethod>();
3232
return method;
3333
}
3434

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

40-
if (properties.ContainsKey("script"))
40+
if (properties.TryGetValue("script", out JToken scriptToken))
4141
{
42-
var scriptProps = JObject.FromObject(properties["script"]).Properties().ToDictionary(p => p.Name, p => p.Value);
42+
var scriptProps = JObject.FromObject(scriptToken).Properties().ToDictionary(p => p.Name, p => p.Value);
4343
if (scriptProps.ContainsKey("inline"))
44-
metric.Script = properties["script"].ToObject<InlineScript>();
45-
else if (scriptProps.ContainsKey("file"))
46-
metric.Script = properties["script"].ToObject<FileScript>();
47-
else if (scriptProps.ContainsKey("id"))
48-
metric.Script = properties["id"].ToObject<IndexedScript>();
44+
metric.Script = scriptToken.ToObject<InlineScript>();
45+
else if (scriptProps.ContainsKey("file"))
46+
metric.Script = scriptToken.ToObject<FileScript>();
47+
else if (scriptProps.TryGetValue("id", out JToken idToken))
48+
metric.Script = idToken.ToObject<IndexedScript>();
4949
}
5050

51-
if (properties.ContainsKey("missing"))
52-
metric.Missing = double.Parse(properties["missing"].ToString());
51+
if (properties.TryGetValue("missing", out JToken missingToken))
52+
metric.Missing = double.Parse(missingToken.ToString());
5353
}
5454

5555
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)

src/Nest/Aggregations/Pipeline/MovingAverage/MovingAverageAggregationJsonConverter.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,11 +83,11 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s
8383

8484
private T GetOrDefault<T>(string key, Dictionary<string, JToken> properties)
8585
{
86-
if (!properties.ContainsKey(key)) return default(T);
86+
if (!properties.TryGetValue(key, out JToken value)) return default(T);
8787
#if DOTNETCORE
88-
return properties[key].ToObject<T>();
88+
return value.ToObject<T>();
8989
#else
90-
return (T)Convert.ChangeType(properties[key], typeof(T));
90+
return (T)Convert.ChangeType(value, typeof(T));
9191
#endif
9292
}
9393

src/Nest/CommonAbstractions/ConnectionSettings/ConnectionSettingsBase.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -200,9 +200,9 @@ public TConnectionSettings MapIdPropertyFor<TDocument>(Expression<Func<TDocument
200200
var memberInfo = new MemberInfoResolver(objectPath);
201201
var fieldName = memberInfo.Members.Single().Name;
202202

203-
if (_idProperties.ContainsKey(typeof(TDocument)))
203+
if (_idProperties.TryGetValue(typeof(TDocument), out var idProperty))
204204
{
205-
if (_idProperties[typeof(TDocument)].Equals(fieldName))
205+
if (idProperty.Equals(fieldName))
206206
return (TConnectionSettings)this;
207207

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

247247
var memberInfo = memberInfoResolver.Members.Last();
248-
if (_propertyMappings.ContainsKey(memberInfo))
248+
if (_propertyMappings.TryGetValue(memberInfo, out var propertyMapping))
249249
{
250250
var newName = mapping.NewName;
251-
var mappedAs = _propertyMappings[memberInfo].Name;
251+
var mappedAs = propertyMapping.Name;
252252
var typeName = typeof(TDocument).Name;
253253
if (mappedAs.IsNullOrEmpty() && newName.IsNullOrEmpty())
254254
throw new ArgumentException($"Property mapping '{e}' on type is already ignored");

src/Nest/CommonOptions/Scripting/ScriptJsonConverter.cs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,32 +20,33 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
2020
if (!dict.HasAny()) return null;
2121

2222
IScript script = null;
23-
if (dict.ContainsKey("inline"))
23+
if (dict.TryGetValue("inline", out JToken inlineToken))
2424
{
25-
var inline = dict["inline"].ToString();
25+
var inline = inlineToken.ToString();
2626
script = new InlineScript(inline);
2727
}
28-
if (dict.ContainsKey("file"))
28+
else if (dict.TryGetValue("file", out JToken fileToken))
2929
{
30-
var file = dict["file"].ToString();
30+
var file = fileToken.ToString();
3131
script = new FileScript(file);
3232
}
33-
if (dict.ContainsKey("id"))
33+
else if (dict.TryGetValue("id", out JToken idToken))
3434
{
35-
var id = dict["id"].ToString();
35+
var id = idToken.ToString();
3636
script = new IndexedScript(id);
3737
}
3838

3939
if (script == null) return null;
4040

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

4646
return script;
4747
}
4848

49-
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotSupportedException();
49+
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) =>
50+
throw new NotSupportedException();
5051
}
5152
}

src/Nest/Modules/SnapshotAndRestore/Repositories/GetRepository/GetRepositoryResponse.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,9 @@ private TRepository Get<TRepository>(string name)
4040
where TRepository : class, ISnapshotRepository
4141
{
4242
if (Repositories == null) return null;
43-
if (!Repositories.ContainsKey(name)) return null;
43+
if (!Repositories.TryGetValue(name, out ISnapshotRepository repository)) return null;
4444

45-
return Repositories[name] as TRepository;
45+
return repository as TRepository;
4646
}
4747
}
4848
}

src/Nest/XPack/Watcher/Condition/ScriptConditionBase.cs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -65,30 +65,30 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
6565
if (!dict.HasAny()) return null;
6666

6767
IScriptCondition scriptCondition = null;
68-
if (dict.ContainsKey("inline"))
68+
if (dict.TryGetValue("inline", out JToken inlineToken))
6969
{
70-
var inline = dict["inline"].ToString();
70+
var inline = inlineToken.ToString();
7171
scriptCondition = new InlineScriptCondition(inline);
7272
}
73-
if (dict.ContainsKey("file"))
73+
else if (dict.TryGetValue("file", out JToken fileToken))
7474
{
75-
var file = dict["file"].ToString();
75+
var file = fileToken.ToString();
7676
#pragma warning disable 618
7777
scriptCondition = new FileScriptCondition(file);
7878
#pragma warning restore 618
7979
}
80-
if (dict.ContainsKey("id"))
80+
else if (dict.TryGetValue("id", out JToken idToken))
8181
{
82-
var id = dict["id"].ToString();
82+
var id = idToken.ToString();
8383
scriptCondition = new IndexedScriptCondition(id);
8484
}
8585

8686
if (scriptCondition == null) return null;
8787

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

9393
return scriptCondition;
9494
}

src/Nest/XPack/Watcher/Input/ChainInput.cs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,13 @@ public ChainInputDescriptor() { }
4242
/// <inheritdoc />
4343
public ChainInputDescriptor Input(string name, Func<InputDescriptor, InputContainer> selector)
4444
{
45-
if (Self.Inputs == null) Self.Inputs = new Dictionary<string, InputContainer>();
46-
47-
if (Self.Inputs.ContainsKey(name))
48-
throw new InvalidOperationException($"An input named '{name}' has already been specified. Choose a different name");
45+
if (Self.Inputs != null)
46+
{
47+
if (Self.Inputs.ContainsKey(name))
48+
throw new InvalidOperationException($"An input named '{name}' has already been specified. Choose a different name");
49+
}
50+
else
51+
Self.Inputs = new Dictionary<string, InputContainer>();
4952

5053
Self.Inputs.Add(name, selector.InvokeOrDefault(new InputDescriptor()));
5154
return this;

src/Nest/XPack/Watcher/Transform/ScriptTransformBase.cs

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -64,33 +64,28 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
6464
if (!dict.HasAny()) return null;
6565

6666
IScriptTransform scriptTransform = null;
67-
if (dict.ContainsKey("inline"))
67+
if (dict.TryGetValue("source", out JToken sourceToken))
6868
{
69-
var inline = dict["inline"].ToString();
69+
var inline = sourceToken.ToString();
7070
scriptTransform = new InlineScriptTransform(inline);
7171
}
72-
else if (dict.ContainsKey("source"))
72+
else if (dict.TryGetValue("file", out var fileToken))
7373
{
74-
var inline = dict["source"].ToString();
75-
scriptTransform = new InlineScriptTransform(inline);
76-
}
77-
else if (dict.ContainsKey("file"))
78-
{
79-
var file = dict["file"].ToString();
74+
var file = fileToken.ToString();
8075
scriptTransform = new FileScriptTransform(file);
8176
}
82-
else if (dict.ContainsKey("id"))
77+
else if (dict.TryGetValue("id", out JToken idToken))
8378
{
84-
var id = dict["id"].ToString();
79+
var id = idToken.ToString();
8580
scriptTransform = new IndexedScriptTransform(id);
8681
}
8782

8883
if (scriptTransform == null) return null;
8984

90-
if (dict.ContainsKey("lang"))
91-
scriptTransform.Lang = dict["lang"].ToString();
92-
if (dict.ContainsKey("params"))
93-
scriptTransform.Params = dict["params"].ToObject<Dictionary<string, object>>();
85+
if (dict.TryGetValue("lang", out JToken langToken))
86+
scriptTransform.Lang = langToken.ToString();
87+
if (dict.TryGetValue("params", out JToken paramsToken))
88+
scriptTransform.Params = paramsToken.ToObject<Dictionary<string, object>>();
9489

9590
return scriptTransform;
9691
}

0 commit comments

Comments
 (0)