泛型與非泛型代碼效能比較

來源:互聯網
上載者:User
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    //非泛型類
    public class RegularStack
    {
        private object[] frames;

        private int pointer = 0;

        public RegularStack(int size)
        {
            this.frames = new object[size];
        }

        //進棧
        public void Push(object frame)
        {
            this.frames[pointer++] = frame;
        }

        //出棧
        public object Pop()
        {
            return this.frames[--pointer];
        }
    }

    //泛型類
    public class GenericStack<T>
    {
        private T[] frames;

        private int pointer = 0;

        public GenericStack(int size)
        {
            this.frames = new T[size];
        }

        //進棧
        public void Push(T frame)
        {
            this.frames[pointer++] = frame;
        }

        //出棧
        public object Pop()
        {
            return this.frames[--pointer];
        }

    }

    public class Rectangle
    {
        public static void Main()
        {
            int iterations = 10000000;   //迴圈次數

            //RegularStack s = new RegularStack(iterations);   //執行非泛型
            GenericStack<int> s = new GenericStack<int>(iterations);   //執行泛型

            DateTime start = DateTime.Now;   //開始時間

            for (int i = 0; i < iterations; i++)
                s.Push(i);                 //進棧

            for (int i = 0; i < iterations; i++)
                s.Pop();                   //出棧

            float ticks = DateTime.Now.Ticks - start.Ticks;
            float duration = ticks / TimeSpan.TicksPerSecond;     //花費時間

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

// int iterations = 100000;   //迴圈次數
// 執行非泛型花費時間: 0.0156
// 執行泛型花費時間:    0.0000

// int iterations = 1000000;   //迴圈次數
// 執行非泛型花費時間: 0.0938
// 執行泛型花費時間:    0.0313

// int iterations = 10000000;   //迴圈次數
// 執行非泛型花費時間: 2.7183
// 執行泛型花費時間:    0.4063

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.