我构思的实验覆盖到下面几个我认为是实际项目中比较有代表性的场景:
1. 访问一个稍大的数据表,遍历所有记录;
2. 生成并操作一个列表;
3. 生成并操作一个字典;
4. 通过反射动态加载并调用一个方法。
C#部分的代码,编译时使用了/debug-和/optimize+:
以下为引用的内容:
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection;
namespace Test
{
class Test
{
public static void Main(string[] args)
{
Console.WriteLine("C#:");
Measure(TestDb, "TestDb");
Measure(TestList, "TestList");
Measure(TestDict, "TestDict");
Measure(TestReflection, "TestReflection");
}
delegate void FuncDelegate();
static void Measure(FuncDelegate func, string funcName)
{
Stopwatch sw = new Stopwatch();
sw.Start();
func();
sw.Stop();
Console.WriteLine(" {0} used {1} ms", funcName, sw.ElapsedMilliseconds);
}
static void TestDb()
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var id = reader["Id"];
var code = reader["Code"];
var cargoCode = reader["CargoCode"];
var length = reader["Length"];
var width = reader["Width"];
var height = reader["Height"];
var vol = reader["Vol"];
var pallet = reader["Pallet"];
}
reader.Close();
cmd.Dispose();
conn.Close();
}
}
static void TestList()
{
var list = new List<string>();
const int count = 100000;
for (int i=0; i<count; i++)
list.Add(string.Format("item{0}", i));
for (int i=count-1; i>=0; i--)
list.RemoveAt(i);
}
static void TestDict()
{
var dict = new Dictionary<string, string>();
const int count = 100000;
for (int i=0; i<count; i++)
dict[string.Format("key{0}", i)] = string.Format("value{0}", i);
for (int i=0; i<count; i++)
dict.Remove(string.Format("key{0}", i));
}
static void TestReflection()
{
Assembly assem = Assembly.LoadFrom("Lib.dll");
Type type = assem.GetType("Lib.TestLib");
const int count = 100000;
ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes);
MethodInfo mi = type.GetMethod("GetMessage");
for (int i=0; i<count; i++)
{
object obj = ci.Invoke(null); // Activator.CreateInstance(type);
mi.Invoke(obj, new object[] { "name" } );
}
}
const string connStr = "Integrated Security=SSPI; Initial Catalog=test; Data Source=.";
&nb
[1] [2] 下一页