我有一个基于 3 个参数缓存数据的方法。例如:
现在我的系统中有很多排列,它们保存在字典中:
Dictionary<string,MyObject> cache;
Run Code Online (Sandbox Code Playgroud)
字典的键是三者的串联,并通过string.format(类似这样的)完成:
public string CreateKey(eState state, int age, int numberOfSibilings)
{
return string.format("{0}#{1}#{2}", state.ToString(), age.ToString(), numberOfSibilings.ToString());
}
Run Code Online (Sandbox Code Playgroud)
eState是一个enum(int)。
该CreateKey方法被调用很多次,并且是性能障碍,因为它string.format不是特别快,并且创建大量不可变字符串并不是最好的方法。
该键可以有空条目,并替换为*. 该CreateKey方法在输入可空值时处理它们并检查它们是否具有值。
我确信有更好的方法来做到这一点。由于eState是 an int,我想过用数学公式以更快的方式创建密钥,但我无法想到快速且独特的东西。
无论如何,我愿意接受您提供的任何解决方案,以尽可能快速且内存友好地创建唯一密钥。
string.format当代码对性能至关重要时,这不是很好。它将参数作为Object类型,这意味着您需要将您的int值类型和其他值类型装箱。
您可以创建一个自定义结构,将其用作字典的键。您需要IEquatable<MyKey>在结构中实现,以便在调用方法时不需要将其装箱Equals。
public struct MyKey : IEquatable<MyKey>
{
public readonly eState State;
public readonly int Age;
public readonly int NumberOfSibilings;
...Implement Equals method here
}
Run Code Online (Sandbox Code Playgroud)
然后使用
Dictionary<MyKey ,MyObject> cache;
public MyKey CreateKey(eState state, int age, int numberOfSibilings)
{
return new MyKey(state, age, numberOfSibilings);
}
Run Code Online (Sandbox Code Playgroud)
这样您就不必在CreateKey方法中创建许多字符串。没有转换;你只需将它们存储为 int 和 enum 本身。没有涉及拳击的电话Enum.ToString(我猜)。在我们的MyKey结构中没有任何拳击。这意味着更好的性能。
如果您正在寻找调试器友好的密钥(在注释中提到),您可以使用DebuggerDisplay属性。
[DebuggerDisplay("State= {State} Age= {Age}")]
public struct MyKey : IEquatable<MyKey>
Run Code Online (Sandbox Code Playgroud)