IronPython和C#执行速度对比
其實(shí)我自己對執(zhí)行速度這個(gè)問題本來并沒有什么興趣,因?yàn)橐郧暗慕?jīng)驗(yàn)告訴我:除非是運(yùn)算密集型的程序,否則腳本語言和編譯型語言使用起來速度沒有多大差別。但是我們公司有個(gè)人知道我的想法以后,天天在我耳邊嚷嚷腳本運(yùn)行速度太慢,那好吧,讓我用實(shí)驗(yàn)來說服你。不過這一試,還真的出現(xiàn)了嚇人一跳的結(jié)果。
我構(gòu)思的實(shí)驗(yàn)覆蓋到下面幾個(gè)我認(rèn)為是實(shí)際項(xiàng)目中比較有代表性的場景:
1. 訪問一個(gè)稍大的數(shù)據(jù)表,遍歷所有記錄;
2. 生成并操作一個(gè)列表;
3. 生成并操作一個(gè)字典;
4. 通過反射動(dòng)態(tài)加載并調(diào)用一個(gè)方法。
C#部分的代碼,編譯時(shí)使用了/debug-和/optimize+:
Codeusing?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=.";
????????
????????const?string?sql?=?"select?*?from?CargoPackageTypes";
????}
}
?IronPython部分的代碼:
Codefrom?__future__?import?with_statement
import?clr,?sys
clr.AddReference('System.Data')
from?System.Data.SqlClient?import?SqlCommand,?SqlConnection
from?System.Diagnostics?import?Stopwatch
from?System.Reflection?import?Assembly
connStr?=?"Integrated?Security=SSPI;?Initial?Catalog=test;?Data?Source=.";
sql?=?"select?*?from?CargoPackageTypes";
def?testDb():
????with?SqlConnection(connStr)?as?conn:
????????conn.Open()
????????
????????cmd?=?SqlCommand(sql,?conn)
????????reader?=?cmd.ExecuteReader()
????????while?reader.Read():
????????????id?=?reader["Id"]
????????????code?=?reader["Code"]
????????????cargoCode?=?reader["CargoCode"]
????????????length?=?reader["Length"]
????????????width?=?reader["Width"]
????????????height?=?reader["Height"]
????????????vol?=?reader["Vol"]
????????????pallet?=?reader["Pallet"]
????????reader.Close()
????????cmd.Dispose()
????????conn.Close()
def?testList():
????lst?=?[]
????count?=?100000
????for?i?in?xrange(count):
????????lst.append('item%d'?%?i)
????for?i?in?xrange(count-1,?-1,?-1):
????????lst.pop(i)
def?testDict():
????d?=?{}
????count?=?100000
????for?i?in?xrange(count):
????????d['key%d'?%?i]?=?'value%d'?%?i
????for?i?in?xrange(count):
????????d.pop('key%d'?%?i)
????????
//www.elivn.com
def?testReflection():
????clr.AddReferenceToFile('Lib.dll')
????from?Lib?import?TestLib
????count?=?100000
????for?i?in?xrange(count):
????????obj??=?TestLib()
????????obj.GetMessage('name')
????????
????????
def?measure(fn):
????sw?=?Stopwatch()
????sw.Start()
????fn()
????sw.Stop()
????print?'????%s?used?%s?ms'?%?(fn.__name__,?sw.ElapsedMilliseconds)
????
print?'Python:'????
measure(testDb)
measure(testList)
measure(testDict)
measure(testReflection)
?運(yùn)行結(jié)果:
?
對于列表和字典的操作,IronPython比C#慢3到4倍,這是意料之中的事情。沒有想到的是訪問數(shù)據(jù)庫的方法,IronPython竟然比C#還要略快,這是事先無論如何都沒有料到的。原來我以為,數(shù)據(jù)庫訪問代碼基本上是純粹的調(diào)用ADO.Net,瓶頸主要是在數(shù)據(jù)庫那一邊,IronPython在方法調(diào)用的時(shí)候應(yīng)該比C#略微慢一點(diǎn)吧,那么總體速度也應(yīng)該稍微慢一點(diǎn)才對。沒想到結(jié)果正好反過來!我也沒有辦法解釋為什么這里IronPython能夠做到比C#還快。不過結(jié)論應(yīng)該很明顯了:訪問數(shù)據(jù)庫的時(shí)候,你無需擔(dān)心IronPython不夠快。我們的項(xiàng)目大多數(shù)時(shí)候效率瓶頸都是出在數(shù)據(jù)庫上面,至于程序語言快一點(diǎn)還是慢一點(diǎn)通常無關(guān)緊要,更何況這里的結(jié)果表明腳本語言有時(shí)候反而可能更快呢。
?對于反射的測試,IronPython則是壓倒性的戰(zhàn)勝了C#。需要說明的一點(diǎn)是我在C#中反射生成對象使用的方法是ConstructorInfo.Invoke()。如果換成Activator.CreateInstance()的話,那么C#的時(shí)間將會(huì)縮減到230~250毫秒,不過即便這樣仍然比IronPython落后一半左右。為什么使用反射時(shí)IronPython比C#快這么多呢?或許因?yàn)樗\(yùn)行的時(shí)候能夠在內(nèi)存中動(dòng)態(tài)生成部分字節(jié)碼,從而跳過反射環(huán)節(jié),所以更快吧。
從這個(gè)實(shí)驗(yàn)的結(jié)果看,IronPython的性能可以說好到超出了我的預(yù)期。因?yàn)橹耙部催^其他一些相關(guān)的性能評(píng)測,比如說Ruby要比Java的運(yùn)行速度慢30倍(這個(gè)比較已經(jīng)有一段時(shí)間了,現(xiàn)在差距應(yīng)該有所縮小),相比之下IronPython的性能簡直可以用十分優(yōu)異來形容了。當(dāng)然腳本語言也有一個(gè)不足的地方,就是加載解釋器的時(shí)候會(huì)帶來幾秒鐘的固定開銷,頻繁修改程序的時(shí)候,這幾秒鐘還是有點(diǎn)讓人難受的。好在以嵌入方式使用IronPython的時(shí)候,引擎只需要加載一次就夠了,所以這個(gè)缺點(diǎn)大體上還是可以接受的。
?補(bǔ)充: 經(jīng)網(wǎng)友提醒,數(shù)據(jù)庫緩存實(shí)際上對測試結(jié)果有一定影響,執(zhí)行相同的sql語句兩次(雖然是在兩個(gè)進(jìn)程),后一次總是比前一次稍微快一點(diǎn),不論使用何種語言。通過改變C#和IronPython測試順序以后的結(jié)果來看,可以認(rèn)為數(shù)據(jù)庫訪問,C#和IronPython的性能基本上是沒有什么差別的。
轉(zhuǎn)載于:https://www.cnblogs.com/seoxs/archive/2011/04/21/2023492.html
總結(jié)
以上是生活随笔為你收集整理的IronPython和C#执行速度对比的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么图片保存类型360 se html
- 下一篇: .NET C# I/O 操作