Click here to Skip to main content
15,885,366 members
Articles / Programming Languages / C#

Iteration Performance in .NET

Rate me:
Please Sign up or sign in to vote.
4.69/5 (19 votes)
20 May 20031 min read 110.8K   567   25  
Article on the relative performance of various methods of iterating through large amounts of data.
using System;
using System.Collections;

namespace Iterations
{
  public class Data : IEnumerable
  {
    private double[] array_;

    public Data(int size) 
    {
      array_ = new double[size];
      Random random = new Random();
      for ( int i = 0; i < size; i++ )
      {
        array_[i] = random.Next();
      }
    }

    public double this[int position]
    {
      get
      {
        return array_[position];
      }
    }

    public double[] Array
    {
      get 
      {
        return array_;
      }
    }

    public DataEnumerator GetEnumerator() 
    {
      return new DataEnumerator( this );
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }
  }
	
  public struct DataEnumerator : IEnumerator
  {
    private Data internal_;
    private int index_;

    public DataEnumerator( Data data ) 
    {
      internal_ = data;
      index_ = 1;
    }

    public double Current
    {
      get
      {
        return internal_.Array[index_];
      }
    }

    object IEnumerator.Current 
    {
      get
      {
        return Current;
      }
    }
  
    public bool MoveNext()
    {
      index_++;
      if ( index_ >= internal_.Array.Length ) 
      {
        return false;
      }
      return true;
    }

    public void Reset()
    {
      index_ = -1;
    }
  }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
CEO CenterSpace Software
United States United States
Trevor has held demanding development positions for a variety of firms using C++, Java, .NET, and other technologies, including Rogue Wave Software, CleverSet, and ProWorks. He is coauthor of The Elements of Java Style , The Elements of C++ Style, and The Elements of C# Style, published by Cambridge University Press. He has also served on a course advisory board of the University of Washington. His teams have won the JavaWorld "GUI Product of the Year" and XML Magazine "Product of the Year" awards. Trevor holds a BSc in Computer Science from the University of British Columbia and a BA in Economics from the University of Western Ontario.

Comments and Discussions