在我的应用程序中,我需要一个大的常量(实际上是静态只读)对象数组.数组在类型的静态构造函数中初始化.
该数组包含超过一千个项目,当首次使用该类型时,我的程序经历了严重的减速.我想知道是否有办法在C#中快速初始化大型数组.
public static class XSampa {
public class XSampaPair : IComparable<XSampaPair> {
public XSampaPair GetReverse() {
return new XSampaPair(Key, Target);
}
public string Key { get; private set; }
public string Target { get; private set; }
internal XSampaPair(string key, string target) {
Key = key;
Target = target;
}
public int CompareTo(XSampaPair other) {
if (other == null)
throw new ArgumentNullException("other",
"Cannot compare with Null.");
if (Key == null)
throw new NullReferenceException("Key is null!");
if (other.Key == null)
throw new NullReferenceException("Key is null!");
if (Key.Length == other.Key.Length)
return string.Compare(Key, other.Key,
StringComparison.InvariantCulture);
return other.Key.Length - other.Key;
}
}
private static readonly XSampaPair[] pairs, reversedPairs;
public static string ParseXSampaToIpa(this string xsampa) {
// Parsing code here...
}
public static string ParseIpaToXSampa(this string ipa) {
// reverse code here...
}
static XSampa() {
pairs = new [] {
new XSampaPair("a", "\u0061"),
new XSampaPair("b", "\u0062"),
new XSampaPair("b_<", "\u0253"),
new XSampaPair("c", "\u0063"),
// And many more pairs initialized here...
};
var temp = pairs.Select(x => x.GetReversed());
reversedPairs = temp.ToArray();
Array.Sort(pairs);
Array.Sort(reversedPairs);
}
}
PS:我使用数组将X-SAMPA语音转录转换为带有相应IPA字符的Unicode字符串.
最佳答案 您可以将完全初始化的onject序列化为二进制文件,将该文件作为资源添加,并在启动时将其加载到阵列中.如果构造函数是CPU密集型的,那么您可能会得到改进.由于您的代码似乎执行某种解析,因此获得体面改进的可能性相当高.