Performance Comparison between generic and non-Generic Code

Source: Internet
Author: User
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. collections;

Namespace consoleapplication1
{
// Non-generic class
Public class regularstack
{
Private object [] frames;

Private int pointer = 0;

Public regularstack (INT size)
{
This. Frames = new object [size];
}

// Stack entry
Public void push (object frame)
{
This. Frames [pointer ++] = frame;
}

// Output Stack
Public object POP ()
{
Return this. Frames [-- pointer];
}
}

// Generic class
Public class genericstack <t>
{
Private T [] frames;

Private int pointer = 0;

Public genericstack (INT size)
{
This. Frames = new T [size];
}

// Stack entry
Public void push (T frame)
{
This. Frames [pointer ++] = frame;
}

// Output Stack
Public object POP ()
{
Return this. Frames [-- pointer];
}

}

Public class rectangle
{
Public static void main ()
{
Int iterations = 10000000; // number of cycles

// Regularstack S = new regularstack (iterations); // executes non-generic
Genericstack <int> S = new genericstack <int> (iterations); // execute generic

Datetime start = datetime. Now; // start time

For (INT I = 0; I <iterations; I ++)
S. Push (I); // Stack

For (INT I = 0; I <iterations; I ++)
S. Pop (); // output Stack

Float ticks = datetime. Now. ticks-start. ticks;
Float duration = ticks/timespan. tickspersecond; // time spent

Console. writeline ("Duration =" + String. Format ("{0: #0.0000}", duration ));

}
}
}

// Int iterations = 100000; // number of cycles
// Execution time of non-generic types: 0.0156
// Execution time of the generic type: 0.0000

// Int iterations = 1000000; // number of cycles
// Execution time of non-generic types: 0.0938
// Execution time of the generic type: 0.0313

// Int iterations = 10000000; // number of cycles
// Execution time of non-generic types: 2.7183
// Execution time of the generic type: 0.4063

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.