博客
关于我
强烈建议你试试无所不能的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

你可能感兴趣的文章
dup和dup2重定向标准输出到文件
查看>>
[转]C#对Excel报表进行操作(读写和基本操作)
查看>>
第一次立会
查看>>
ActiveMQ使用教程
查看>>
图片的拷贝
查看>>
python函数2
查看>>
PHP 写文件的例子
查看>>
数据库的增删改查
查看>>
es6相关知识点
查看>>
php生成验证码 参考PHP手册
查看>>
[Hadoop]Hadoop章2 HDFS原理及读写过程
查看>>
344. Reverse String
查看>>
迭代最近点算法 Iterative Closest Points
查看>>
2015AppStore 上传步骤及常见问题
查看>>
[lintcode easy]Product of Array Exclude Itself
查看>>
OSI七层模型详解
查看>>
Vi编辑器常用命令
查看>>
ACM学习历程——UVA442 Matrix Chain Multiplication(栈)
查看>>
CSS 布局
查看>>
Firefox的缓存问题
查看>>