最快的arrays初始化?

在我的应用程序中,我需要一个大的常量(实际上是static readonly )对象数组。 数组在类型的静态构造函数中初始化。

该数组包含超过一千个项目,当首次使用该类型时,我的程序经历了严重的减速。 我想知道是否有办法在C#中快速初始化大型数组。

 public static class XSampa { public class XSampaPair : IComparable { 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_ x.GetReversed()); reversedPairs = temp.ToArray(); Array.Sort(pairs); Array.Sort(reversedPairs); } } 

PS:我使用数组将X-SAMPA语音转录转换为带有相应IPA字符的Unicode字符串。

您可以将完全初始化的onject序列化为二进制文件,将该文件作为资源添加,并在启动时将其加载到arrays中。 如果构造函数是CPU密集型的,那么您可能会得到改进。 由于您的代码似乎执行某种解析,因此获得体面改进的可能性相当高。

你可以使用一个IEnumerable来让你IEnumerable屈服,只在需要的时候返回枚举。

这个问题是你无法像使用数组那样索引它。