【发布时间】:2012-04-22 23:04:17
【问题描述】:
在我的一个应用程序中,我需要一个大型常量(实际上是static readonly)对象数组。数组在类型的静态构造函数中初始化。
该数组包含一千多个项目,当第一次使用该类型时,我的程序遇到了严重的减速。我想知道是否有办法在 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 字符串。
【问题讨论】:
-
是否可以使用
IEnumerable<yourobj>,以便您可以根据需要懒惰地返回数组? -
@jb 的解决方案很好,但是如果你不想修改任何代码,你可以在应用程序启动时简单地初始化它,也许是闪屏..
-
抱歉修改后请忽略
-
不能有闪屏,一切都必须能在服务器端运行。
标签: c# arrays performance