当前位置: 编程技术>.net/c#/asp.net
C#泛型与非泛型性能比较 类型安全的实例代码
来源: 互联网 发布时间:2014-08-30
本文导语: 例1,c#泛型与非泛型性能比较 代码示例: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace ConsoleApplication { class Program { static int length = 1000 * 1000; static void Main(string[] args) { in...
例1,c#泛型与非泛型性能比较
代码示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication
{
class Program
{
static int length = 1000 * 1000;
static void Main(string[] args)
{
int iteration=10;//方法执行次数
CodeTimer.Time("值类型处理-泛型方法", iteration, Test1);
CodeTimer.Time("值类型处理-非泛型方法", iteration, Test2);
//CodeTimer.Time("引用类型处理-泛型方法", iteration, Test3);
//CodeTimer.Time("引用类型处理-非泛型方法", iteration, Test4);
Console.ReadKey();
}
///
/// 值类型泛型方法
///
static void Test1()
{
List l = new List();
for (int i = 0; i < length; i++)
{
l.Add(i);
int a = l[i];
}
l = null;
}
///
/// 值类型非泛型方法
///
static void Test2()
{
ArrayList a = new ArrayList();
for (int i = 0; i < length; i++)
{
a.Add(i);
int s = (int)a[i];
}
a = null;
}
///
/// 引用类型泛型方法
///
static void Test3()
{
List l = new List();
for (int i = 0; i < length; i++)
{
l.Add("l");
string s = l[i];
}
}
///
/// 引用类型的非泛型方法
///
static void Test4()
{
ArrayList a = new ArrayList();
for(int i=0;i
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication
{
class Program
{
static int length = 1000 * 1000;
static void Main(string[] args)
{
int iteration=10;//方法执行次数
CodeTimer.Time("值类型处理-泛型方法", iteration, Test1);
CodeTimer.Time("值类型处理-非泛型方法", iteration, Test2);
//CodeTimer.Time("引用类型处理-泛型方法", iteration, Test3);
//CodeTimer.Time("引用类型处理-非泛型方法", iteration, Test4);
Console.ReadKey();
}
///
/// 值类型泛型方法
///
static void Test1()
{
List l = new List();
for (int i = 0; i < length; i++)
{
l.Add(i);
int a = l[i];
}
l = null;
}
///
/// 值类型非泛型方法
///
static void Test2()
{
ArrayList a = new ArrayList();
for (int i = 0; i < length; i++)
{
a.Add(i);
int s = (int)a[i];
}
a = null;
}
///
/// 引用类型泛型方法
///
static void Test3()
{
List l = new List();
for (int i = 0; i < length; i++)
{
l.Add("l");
string s = l[i];
}
}
///
/// 引用类型的非泛型方法
///
static void Test4()
{
ArrayList a = new ArrayList();
for(int i=0;i