最快阵列初始化? [英] Quickest Array Initialization?
问题描述
在我的一个应用,我需要一个大的常数(实际上是静态只读
)对象的数组。数组初始化在类型的静态构造函数。
In an application of mine, I need a large constant (actually static readonly
) array of objects. The array is initialized in the type's static constructor.
该数组包含千余项,并在第一次使用的类型,我的程序出现严重放缓。我想知道是否有在C#中快速初始化一个大阵的方法。
The array contains more than a thousand items, and when the type is first used, my program experiences a serious slowdown. I would like to know if there is a way to initialise a large array quickly in 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拼音转换为统一code字符串与相应的IPA字符。
PS: I use to array to convert X-SAMPA phonetic transcription to a Unicode string with the corresponding IPA characters.
推荐答案
您可以序列完全初始化onject成一个二进制文件,添加文件作为一种资源,并将其加载到你的阵列上启动。如果你的构造函数是CPU密集型的,你可能会得到改善。由于您的code能够进行某种形式的解析,得到一个像样的改进的机会有相当高的。
You can serialize a completely initialized onject into a binary file, add that file as a resource, and load it into your array on startup. If your constructors are CPU-intensive, you might get an improvement. Since your code appears to perform some sort of parsing, the chances of getting a decent improvement there are fairly high.
这篇关于最快阵列初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!