Skip to content

Commit

Permalink
Eliminate many double or triple dictionary lookups
Browse files Browse the repository at this point in the history
  • Loading branch information
siimav committed Aug 7, 2024
1 parent 1cc10a3 commit cdfcf1a
Show file tree
Hide file tree
Showing 28 changed files with 112 additions and 119 deletions.
12 changes: 6 additions & 6 deletions source/CC_RemoteTech/RemoteTechProgressTracker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,15 +172,15 @@ private void Initialize()
// Add celestial bodies to listing
foreach (CelestialBody cb in FlightGlobals.Bodies)
{
if (!celestialBodies.ContainsKey(cb))
if (!celestialBodies.TryGetValue(cb, out CelestialBodyInfo cbi))
{
CelestialBodyInfo cbi = new CelestialBodyInfo();
cbi = new CelestialBodyInfo();
cbi.body = cb;
cbi.coverage = 0;
celestialBodies[cb] = cbi;
}

celestialBodies[cb].sat = RTCore.Instance.Satellites[cb.Guid()];
cbi.sat = RTCore.Instance.Satellites[cb.Guid()];
}

initialized = true;
Expand Down Expand Up @@ -343,9 +343,9 @@ public override void OnSave(ConfigNode node)
public static double GetCoverage(CelestialBody body)
{
// Calculate the coverage
if (Instance != null && Instance.celestialBodies.ContainsKey(body))
if (Instance != null && Instance.celestialBodies.TryGetValue(body, out CelestialBodyInfo cbi))
{
UInt32 cov = Instance.celestialBodies[body].coverage;
UInt32 cov = cbi.coverage;
UInt32 count = 0;
while (cov > 0)
{
Expand All @@ -365,7 +365,7 @@ public static double GetCoverage(CelestialBody body)
/// <returns>The range</returns>
public double ActiveRange(CelestialBody body)
{
return celestialBodies.ContainsKey(body) ? celestialBodies[body].activeRange : 0.0;
return celestialBodies.TryGetValue(body, out CelestialBodyInfo cbi) ? cbi.activeRange : 0.0;
}

/// <summary>
Expand Down
11 changes: 6 additions & 5 deletions source/ContractConfigurator/Behaviour/Expression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,10 @@ protected override void OnCompleted()

protected override void OnParameterStateChange(ContractParameter param)
{
if (param.ID != null && param.State == ParameterState.Complete && onParameterComplete.ContainsKey(param.ID))
if (param.ID != null && param.State == ParameterState.Complete &&
onParameterComplete.TryGetValue(param.ID, out List<ExpVal> exprs))
{
ExecuteExpressions(onParameterComplete[param.ID]);
ExecuteExpressions(exprs);
onParameterComplete[param.ID].Clear();
}
}
Expand Down Expand Up @@ -172,11 +173,11 @@ protected override void OnLoad(ConfigNode configNode)
// Store it for later
if (child.name == "PARAMETER_COMPLETED")
{
if (!onParameterComplete.ContainsKey(parameter))
if (!onParameterComplete.TryGetValue(parameter, out List<ExpVal> list))
{
onParameterComplete[parameter] = new List<ExpVal>();
onParameterComplete[parameter] = list = new List<ExpVal>();
}
onParameterComplete[parameter].Add(expVal);
list.Add(expVal);
}
else
{
Expand Down
8 changes: 4 additions & 4 deletions source/ContractConfigurator/BehaviourFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,10 @@ public static void Register(Type factoryType, string typeName)
{
LoggingUtil.LogDebug(typeof(BehaviourFactory), "Registering behaviour factory class {0} for handling BEHAVIOUR nodes with type = {1}.", factoryType.FullName, typeName);

if (factories.ContainsKey(typeName))
if (factories.TryGetValue(typeName, out Type fType))
{
LoggingUtil.LogError(typeof(BehaviourFactory), "Cannot register {0}[{1}] to handle type {2}: already handled by {3}[{4}]",
factoryType.FullName, factoryType.Module, typeName, factories[typeName].FullName, factories[typeName].Module);
factoryType.FullName, factoryType.Module, typeName, fType.FullName, fType.Module);
}
else
{
Expand Down Expand Up @@ -147,7 +147,7 @@ public static bool GenerateBehaviourFactory(ConfigNode behaviourConfig, Contract
behaviourFactory = new InvalidBehaviourFactory();
valid = false;
}
else if (!factories.ContainsKey(type))
else if (!factories.TryGetValue(type, out Type fType))
{
LoggingUtil.LogError(typeof(ParameterFactory), "CONTRACT_TYPE '{0}', BEHAVIOUR '{1}' of type '{2}': Unknown behaviour '{3}'.",
contractType.name, behaviourConfig.GetValue("name"), behaviourConfig.GetValue("type"), type);
Expand All @@ -157,7 +157,7 @@ public static bool GenerateBehaviourFactory(ConfigNode behaviourConfig, Contract
else
{
// Create an instance of the factory
behaviourFactory = (BehaviourFactory)Activator.CreateInstance(factories[type]);
behaviourFactory = (BehaviourFactory)Activator.CreateInstance(fType);
}

// Set attributes
Expand Down
2 changes: 1 addition & 1 deletion source/ContractConfigurator/ContractGroup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public static string GroupDisplayName(string groupName)
return "";
}

ContractGroup group = contractGroups.ContainsKey(groupName) ? contractGroups[groupName] : null;
contractGroups.TryGetValue(groupName, out ContractGroup group);
return group == null ? "" : group.displayName;
}

Expand Down
10 changes: 5 additions & 5 deletions source/ContractConfigurator/ContractRequirement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ public static ContractRequirement LoadRequirement(ConfigNode configNode)
{
return null;
}
Type type = requirementTypes.ContainsKey(typeName) ? requirementTypes[typeName] : null;
requirementTypes.TryGetValue(typeName, out Type type);
if (type == null)
{
throw new Exception("No ContractRequirement with type = '" + typeName + "'.");
Expand Down Expand Up @@ -280,10 +280,10 @@ public static void Register(Type crType, string typeName)
{
LoggingUtil.LogDebug(typeof(ContractRequirement), "Registering ContractRequirement class {0} for handling REQUIREMENT nodes with type = {1}.", crType.FullName, typeName);

if (requirementTypes.ContainsKey(typeName))
if (requirementTypes.TryGetValue(typeName, out Type rType))
{
LoggingUtil.LogError(typeof(ContractRequirement), "Cannot register {0}[{1}] to handle type {2}: already handled by {3}[{4}]",
crType.FullName, crType.Module, typeName, requirementTypes[typeName].FullName, requirementTypes[typeName].Module);
crType.FullName, crType.Module, typeName, rType.FullName, rType.Module);
}
else
{
Expand Down Expand Up @@ -319,7 +319,7 @@ public static bool GenerateRequirement(ConfigNode configNode, ContractType contr
requirement = new InvalidContractRequirement();
valid = false;
}
else if (!requirementTypes.ContainsKey(type))
else if (!requirementTypes.TryGetValue(type, out Type rType))
{
LoggingUtil.LogError(typeof(ParameterFactory), "CONTRACT_TYPE '{0}', REQUIREMENT '{1}' of type '{2}': Unknown requirement '{3}'.",
contractType.name, configNode.GetValue("name"), configNode.GetValue("type"), type);
Expand All @@ -329,7 +329,7 @@ public static bool GenerateRequirement(ConfigNode configNode, ContractType contr
else
{
// Create an instance of the ContractRequirement
requirement = (ContractRequirement)Activator.CreateInstance(requirementTypes[type]);
requirement = (ContractRequirement)Activator.CreateInstance(rType);
}

// Set attributes
Expand Down
7 changes: 3 additions & 4 deletions source/ContractConfigurator/ContractType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ public static IEnumerable<string> AllValidContractTypeNames

public static ContractType GetContractType(string name)
{
if (name != null && contractTypes.ContainsKey(name))
if (name != null && contractTypes.TryGetValue(name, out ContractType ct))
{
return contractTypes[name];
return ct;
}
return null;
}
Expand Down Expand Up @@ -881,9 +881,8 @@ public void ResearchBodiesCheck(ConfiguredContract contract)
Dictionary<CelestialBody, RBWrapper.CelestialBodyInfo> bodyInfoDict = RBWrapper.RBactualAPI.CelestialBodies;
foreach (CelestialBody body in contract.ContractBodies)
{
if (bodyInfoDict.ContainsKey(body) && !body.isHomeWorld)
if (!body.isHomeWorld && bodyInfoDict.TryGetValue(body, out RBWrapper.CelestialBodyInfo bodyInfo))
{
RBWrapper.CelestialBodyInfo bodyInfo = bodyInfoDict[body];
if (!bodyInfo.isResearched)
{
throw new ContractRequirementException(StringBuilderCache.Format("Research Bodies: {0} has not yet been researched.", body.name));
Expand Down
10 changes: 5 additions & 5 deletions source/ContractConfigurator/ExpressionParser/BaseParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,9 +190,9 @@ public static void RegisterParserType(Type objectType, Type parserType)
/// <returns>An instance of the expression parser, or null if none can be created</returns>
public static ExpressionParser<T> GetParser<T>()
{
if (parserTypes.ContainsKey(typeof(T)))
if (parserTypes.TryGetValue(typeof(T), out Type t))
{
return (ExpressionParser<T>)Activator.CreateInstance(parserTypes[typeof(T)]);
return (ExpressionParser<T>)Activator.CreateInstance(t);
}
else if (typeof(T).IsEnum)
{
Expand Down Expand Up @@ -257,11 +257,11 @@ protected void Init(string expression)
/// <param name="method">The callable function.</param>
protected static void RegisterGlobalFunction(Function function)
{
if (!globalFunctions.ContainsKey(function.Name))
if (!globalFunctions.TryGetValue(function.Name, out List<Function> list))
{
globalFunctions[function.Name] = new List<Function>();
globalFunctions[function.Name] = list = new List<Function>();
}
globalFunctions[function.Name].Add(function);
list.Add(function);
}

protected static Type GetRequiredType(Exception e)
Expand Down
10 changes: 5 additions & 5 deletions source/ContractConfigurator/ExpressionParser/DataNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,14 @@ public object this[string s]
{
DataNode node = NodeForKey(ref s);
lastModified = Time.fixedTime;
if (!node.data.ContainsKey(s))
if (!node.data.TryGetValue(s, out Value val))
{
node.data[s] = new Value(value);
}
else
{
node.data[s].value = value;
node.data[s].initialized = true;
val.value = value;
val.initialized = true;
}

LoggingUtil.LogVerbose(this, "DataNode[{0}], storing {1} = {2}", node.name, s, OutputValue(value));
Expand Down Expand Up @@ -152,7 +152,7 @@ public void SetDeterministic(string s, bool value)
public bool IsInitialized(string key)
{
DataNode node = NodeForKey(ref key);
return node.data.ContainsKey(key) && node.data[key] != null && node.data[key].initialized;
return node.data.TryGetValue(key, out Value val) && val != null && val.initialized;
}

public void BlankInit(string key, Type type)
Expand All @@ -167,7 +167,7 @@ public void BlankInit(string key, Type type)
public Type GetType(string key)
{
DataNode node = NodeForKey(ref key);
return node.data.ContainsKey(key) && node.data[key] != null ? node.data[key].type : null;
return node.data.TryGetValue(key, out Value val) && val != null ? val.type : null;
}

public DataNode Parent
Expand Down
28 changes: 13 additions & 15 deletions source/ContractConfigurator/ExpressionParser/ExpressionParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ public ExpressionParser()
/// <param name="method">The callable method.</param>
public static void RegisterMethod(Function method)
{
if (!classMethods.ContainsKey(method.Name))
if (!classMethods.TryGetValue(method.Name, out List<Function> list))
{
classMethods[method.Name] = new List<Function>();
classMethods[method.Name] = list = new List<Function>();
}
classMethods[method.Name].Add(method);
list.Add(method);
}

/// <summary>
Expand All @@ -42,11 +42,11 @@ public static void RegisterMethod(Function method)
/// <param name="method">The callable function.</param>
public static void RegisterLocalFunction(Function function)
{
if (!classFunctions.ContainsKey(function.Name))
if (!classFunctions.TryGetValue(function.Name, out List<Function> list))
{
classFunctions[function.Name] = new List<Function>();
classFunctions[function.Name] = list = new List<Function>();
}
classFunctions[function.Name].Add(function);
list.Add(function);
}

/// <summary>
Expand All @@ -56,16 +56,16 @@ public static void RegisterLocalFunction(Function function)
/// <returns>Enumeration of functions</returns>
public IEnumerable<Function> GetFunctions(string name)
{
if (classFunctions.ContainsKey(name))
if (classFunctions.TryGetValue(name, out List<Function> list))
{
foreach (Function f in classFunctions[name])
foreach (Function f in list)
{
yield return f;
}
}
if (globalFunctions.ContainsKey(name))
if (globalFunctions.TryGetValue(name, out List<Function> list2))
{
foreach (Function f in globalFunctions[name])
foreach (Function f in list2)
{
yield return f;
}
Expand Down Expand Up @@ -826,10 +826,8 @@ public void ParseToken(string expected)
public virtual T ParseVarOrIdentifier(Token token)
{
// Look it up in temporary variables
if (tempVariables.ContainsKey(token.sval))
if (tempVariables.TryGetValue(token.sval, out KeyValuePair<object, Type> pair))
{
KeyValuePair<object, Type> pair = tempVariables[token.sval];

// Check for a method call before we start messing with types
Token methodToken = ParseMethodToken();
if (methodToken != null)
Expand Down Expand Up @@ -1001,9 +999,9 @@ public IEnumerable<object> GetCalledFunction(string functionName, ref Function s
}
else
{
if (classMethods.ContainsKey(functionName))
if (classMethods.TryGetValue(functionName, out List<Function> list))
{
methods = classMethods[functionName].ToList();
methods = list.ToList();
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ protected static T SelectUnique(List<T> input)
// Get details from the base parser
ContractType contractType = BaseParser.currentParser.currentDataNode.Root.Factory as ContractType;
string key = BaseParser.currentParser.currentKey;
DataNode.UniquenessCheck uniquenessCheck = contractType.uniquenessChecks.ContainsKey(key) ? contractType.uniquenessChecks[key] : DataNode.UniquenessCheck.NONE;
DataNode.UniquenessCheck uniquenessCheck = contractType.uniquenessChecks.TryGetValue(key, out DataNode.UniquenessCheck uc) ? uc : DataNode.UniquenessCheck.NONE;
DataNode dataNode = BaseParser.currentParser.currentDataNode;

// Provide warning of a better method
Expand Down
8 changes: 4 additions & 4 deletions source/ContractConfigurator/ExpressionParser/Wrappers/Tech.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public static Tech GetTech(string techID)
return null;
}

return allTech.ContainsKey(techID) ? allTech[techID] : null;
return allTech.TryGetValue(techID, out Tech tech) ? tech : null;
}

public bool IsUnlocked()
Expand Down Expand Up @@ -113,12 +113,12 @@ private static bool SetupTech()
foreach (ConfigNode parentNode in techNode.GetNodes("Parent"))
{
string parentID = parentNode.GetValue("parentID");
if (allTech.ContainsKey(parentID))
if (allTech.TryGetValue(parentID, out Tech tech))
{
hasParent = true;
allTech[parentID].children.Add(current);
tech.children.Add(current);

current.level = allTech[parentID].level + 1;
current.level = tech.level + 1;
}
}

Expand Down
9 changes: 4 additions & 5 deletions source/ContractConfigurator/MissionControlUI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,9 @@ public GroupContainer(Type stockContractType)
this.stockContractType = stockContractType;

// Determine the agent
if (contractAgents.ContainsKey(stockContractType.Name))
if (contractAgents.TryGetValue(stockContractType.Name, out Agent tmp))
{
agent = contractAgents[stockContractType.Name];
agent = tmp;
}
}

Expand Down Expand Up @@ -177,7 +177,7 @@ public static string DisplayName(Type type)
LoadConfig();
}

return contractNames.ContainsKey(type.Name) ? contractNames[type.Name] : type.Name;
return contractNames.TryGetValue(type.Name, out string n) ? n : type.Name;
}

public string OrderKey()
Expand Down Expand Up @@ -1621,9 +1621,8 @@ protected string ResearchBodyText(ContractType contractType)
Dictionary<CelestialBody, RBWrapper.CelestialBodyInfo> bodyInfoDict = RBWrapper.RBactualAPI.CelestialBodies;
foreach (CelestialBody body in contractType.contractBodies)
{
if (bodyInfoDict.ContainsKey(body) && !body.isHomeWorld)
if (!body.isHomeWorld && bodyInfoDict.TryGetValue(body, out RBWrapper.CelestialBodyInfo bodyInfo))
{
RBWrapper.CelestialBodyInfo bodyInfo = bodyInfoDict[body];
// Must have researched <<1>>
output += RequirementLine(Localizer.Format("#cc.mcui.req.researchBody", body.displayName), bodyInfo.isResearched);
}
Expand Down
Loading

0 comments on commit cdfcf1a

Please sign in to comment.