Geeks With Blogs
Abhishek Anand Bits & Bytes about .net technology framework.

Although both arrays and collections are used in a similar fashion, there are some performance considerations when choosing one over the other. Below are some design guidelines:

1-     You should not return an internal instance of an array. This allows calling code to change the array. The following example demonstrates how the array delimiters can be altered by the calling code.

    public sealed class DocParser

    {

        private DocParser(){}

        private static char[] delimiters = {',', '-', ' '}

        public char[] Delimiters { get { return delimiters; } }

      

        public static char[] GetDelimiters()

        {

            return delimiters;

        }

    }

    //The following line can be used to change the values in the array.

    DocParser.GetDelimiters[0] = '*';

 

2-     You should use collections to avoid code inefficiencies caused by properties that return arrays. In the following code example, each call to the Delimiters property creates a copy of the array resulting in 2n+1 copies of the array

    for (int i = 0; i < DocParser.Delimiters.Count; i++)

    {

        DoSomething(DocParser.Delimiters[i]);

    }

 

3-     Do not use readonly fields of arrays. Although it makes the array read-only, the elements in the array can still be changed. Check the following code snippet

    public sealed class DocParser

    {

       private DocParser(){}

       public static readonly char[] Delimiters = {',', '-', ' '}

    }

    //The following line can be used to change the values in the array.

    DocParser.Delimiters[0] = '*';

 

Posted on Wednesday, November 20, 2013 4:29 PM .net , collections , arrays , c# | Back to top


Comments on this post: Usage of Arrays

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Abhishek Anand | Powered by: GeeksWithBlogs.net