Skip to content

Commit 3a317cf

Browse files
Henr1k80SukharevAndrey
authored andcommitted
Avoid doing multiple dictionary lookups (get key hash, find bucket, iterate bucket) (elastic#3580)
(cherry picked from commit 750b4ec)
1 parent 27e2053 commit 3a317cf

File tree

12 files changed

+69
-72
lines changed

12 files changed

+69
-72
lines changed

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

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

8484
return http != null;
8585
}

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/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: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,37 +17,37 @@ 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("source") || scriptProps.ContainsKey("inline"))
44-
metric.Script = properties["script"].ToObject<InlineScript>();
45-
else if (scriptProps.ContainsKey("id"))
46-
metric.Script = properties["id"].ToObject<IndexedScript>();
44+
metric.Script = scriptToken.ToObject<InlineScript>();
45+
else if (scriptProps.TryGetValue("id", out JToken idToken))
46+
metric.Script = idToken.ToObject<IndexedScript>();
4747
}
4848

49-
if (properties.ContainsKey("missing"))
50-
metric.Missing = double.Parse(properties["missing"].ToString());
49+
if (properties.TryGetValue("missing", out JToken missingToken))
50+
metric.Missing = double.Parse(missingToken.ToString());
5151
}
5252

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

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

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,8 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s
7979

8080
private T GetOrDefault<T>(string key, Dictionary<string, JToken> properties)
8181
{
82-
if (!properties.ContainsKey(key)) return default(T);
83-
84-
return properties[key].ToObject<T>();
85-
86-
//TODO decide if this works too for .NET core, looks like it
87-
//return (T)Convert.ChangeType(properties[key], typeof(T));
82+
if (!properties.TryGetValue(key, out JToken value)) return default(T);
83+
return value.ToObject<T>();
8884
}
8985

9086
private GapPolicy? GetGapPolicy(Dictionary<string, JToken> properties)

src/Nest/CommonAbstractions/ConnectionSettings/ConnectionSettingsBase.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -173,9 +173,9 @@ private void MapIdPropertyFor<TDocument>(Expression<Func<TDocument, object>> obj
173173
var memberInfo = new MemberInfoResolver(objectPath);
174174
var fieldName = memberInfo.Members.Single().Name;
175175

176-
if (_idProperties.ContainsKey(typeof(TDocument)))
176+
if (_idProperties.TryGetValue(typeof(TDocument), out string idPropertyFieldName))
177177
{
178-
if (_idProperties[typeof(TDocument)].Equals(fieldName)) return;
178+
if (idPropertyFieldName.Equals(fieldName)) return;
179179

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

194-
if (_routeProperties.ContainsKey(typeof(TDocument)))
194+
if (_routeProperties.TryGetValue(typeof(TDocument), out string routePropertyFieldName))
195195
{
196-
if (_routeProperties[typeof(TDocument)].Equals(fieldName)) return;
196+
if (routePropertyFieldName.Equals(fieldName)) return;
197197

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

218218
var memberInfo = memberInfoResolver.Members.Last();
219-
if (_propertyMappings.ContainsKey(memberInfo))
219+
if (_propertyMappings.TryGetValue(memberInfo, out IPropertyMapping propertyMapping))
220220
{
221221
var newName = mapping.NewName;
222-
var mappedAs = _propertyMappings[memberInfo].Name;
222+
var mappedAs = propertyMapping.Name;
223223
var typeName = typeof(TDocument).Name;
224224
if (mappedAs.IsNullOrEmpty() && newName.IsNullOrEmpty())
225225
throw new ArgumentException($"Property mapping '{e}' on type is already ignored");

src/Nest/CommonOptions/Scripting/ScriptJsonConverter.cs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,28 +20,28 @@ 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("source"))
28+
if (dict.TryGetValue("source", out JToken sourceToken))
2929
{
30-
var inline = dict["source"].ToString();
30+
var inline = sourceToken.ToString();
3131
script = new InlineScript(inline);
3232
}
33-
if (dict.ContainsKey("id"))
33+
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
}

src/Nest/IndexModules/IndexSettings/Settings/IndexSettingsConverter.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -256,9 +256,8 @@ private static void Set<T>(IIndexSettings s, IDictionary<string, JProperty> sett
256256
JsonSerializer serializer = null
257257
)
258258
{
259-
if (!settings.ContainsKey(key)) return;
259+
if (!settings.TryGetValue(key, out JProperty v)) return;
260260

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

274-
var v = settings[key];
275273
if (v.Value is JArray)
276274
{
277275
var value = serializer == null ? v.Value.ToObject<TArray>() : v.Value.ToObject<TArray>(serializer);

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
@@ -68,28 +68,28 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
6868
if (!dict.HasAny()) return null;
6969

7070
IScriptCondition scriptCondition = null;
71-
if (dict.ContainsKey("inline"))
71+
if (dict.TryGetValue("inline", out JToken inlineToken))
7272
{
73-
var inline = dict["inline"].ToString();
73+
var inline = inlineToken.ToString();
7474
scriptCondition = new InlineScriptCondition(inline);
7575
}
76-
if (dict.ContainsKey("source"))
76+
if (dict.TryGetValue("source", out JToken sourceToken))
7777
{
78-
var inline = dict["source"].ToString();
78+
var inline = sourceToken.ToString();
7979
scriptCondition = new InlineScriptCondition(inline);
8080
}
81-
if (dict.ContainsKey("id"))
81+
if (dict.TryGetValue("id", out JToken idToken))
8282
{
83-
var id = dict["id"].ToString();
83+
var id = idToken.ToString();
8484
scriptCondition = new IndexedScriptCondition(id);
8585
}
8686

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

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

9494
return scriptCondition;
9595
}

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 & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -67,28 +67,28 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
6767
if (!dict.HasAny()) return null;
6868

6969
IScriptTransform scriptTransform = null;
70-
if (dict.ContainsKey("inline"))
70+
if (dict.TryGetValue("inline", out JToken inlineToken))
7171
{
72-
var inline = dict["inline"].ToString();
72+
var inline = inlineToken.ToString();
7373
scriptTransform = new InlineScriptTransform(inline);
7474
}
75-
if (dict.ContainsKey("source"))
75+
if (dict.TryGetValue("source", out JToken sourceToken))
7676
{
77-
var inline = dict["source"].ToString();
77+
var inline = sourceToken.ToString();
7878
scriptTransform = new InlineScriptTransform(inline);
7979
}
80-
if (dict.ContainsKey("id"))
80+
if (dict.TryGetValue("id", out JToken idToken))
8181
{
82-
var id = dict["id"].ToString();
82+
var id = idToken.ToString();
8383
scriptTransform = new IndexedScriptTransform(id);
8484
}
8585

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

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

9393
return scriptTransform;
9494
}

0 commit comments

Comments
 (0)