4

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.

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: I use to array to convert X-SAMPA phonetic transcription to a Unicode string with the corresponding IPA characters.

4

2 回答 2

2

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.

于 2012-04-22T23:20:00.060 回答
0

You could use an IEnumerable<yourobj> which would let you lazily yield return the enumerable only as needed.

The problem with this is you won't be able to index into it like you could using the array.

于 2012-04-22T23:21:16.477 回答