博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
泛型与非泛型代码性能比较
阅读量:4597 次
发布时间:2019-06-09

本文共 1523 字,大约阅读时间需要 5 分钟。

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

转载于:https://www.cnblogs.com/lc329857895/archive/2008/01/18/1044743.html

你可能感兴趣的文章
[lintcode easy]Product of Array Exclude Itself
查看>>
OSI七层模型详解
查看>>
Vi编辑器常用命令
查看>>
ACM学习历程——UVA442 Matrix Chain Multiplication(栈)
查看>>
CSS 布局
查看>>
Firefox的缓存问题
查看>>
ENSP错误
查看>>
Java MVC 分页实例
查看>>
响应式布局1--媒体查询和-webkit-min-device-pixel-ratio
查看>>
CocoaPods应用于iOS项目框架管理方案
查看>>
POJ-3233 Matrix Power Series 矩阵A^1+A^2+A^3...求和转化
查看>>
IIS是如何处理ASP.NET请求的
查看>>
SSIS之Foreach循环容器应用
查看>>
局域网内访问机器时出现“未授予在次计算机上的请求登陆类型”
查看>>
硬币组合问题
查看>>
(9)模板层 - templates(模板语言、语法、取值、过滤器、变量的使用)
查看>>
P3469 [POI2008]BLO-Blockade
查看>>
P1171 售货员的难题
查看>>
DevOps之持续交付
查看>>
有趣的数学(一)
查看>>