05年時,在微軟的Rico Mariani做了一次實際應用的C#和C++的性能比較。事情起源於微軟著名的元老Raymond Chen(在下敬仰的超級牛人)用C++寫了一個英漢詞典程序,來描述講解優化C++程序的過程。他從一個代碼簡單直觀的版本開始,不斷測試優化,直到達到滿意的性能。Rico Mariani使用相同的方式,但是使用C#做了相同的程序。結果是,Mariani的最初的簡單直觀版本的速度幾乎是Chen的最初C++版本的十倍;而對於優化的終極版本,Chen重寫了文件IO,重寫了字符串類,使用了自定義的內存分配器,使得C++版本的速度是C#版本的兩倍。
簡單的說C#的設計目標之一就是可以使簡單直觀的代碼具有較高的效率,而且它確實實現了這個目標;而C++允許我們使用任何手段來提高效率,只要願意做出足夠的努力。
原文:
A few years ago, Rico Mariani (at Microsoft) did really interesting performance comparison between C# and C++.
It started when Raymond Chen (one of the most important engineers at Microsoft, and in the CS universe generally) wrote a Chinese/English dictionary application in C++ to illustrate his process for optimizing C++ code. He started with a simple, intuitive version of the code, and then he incrementally profiled and optimized the bottlenecks until he was happy with the performance.
Rico Mariani took a similar tack, writing a simple, intuitive version in C#, and then optimizing its bottlenecks.
Surprisingly, Mariani''s original C# implementation is almost ten times as fast as Chen''s original C++ implementation, without having to resort to any counterintuitive hacks.
Eventually, Chen rewrote the file I/O library, implemented his own string class, and used a custom memory allocator. Only AFTER jumping through all those hoops, the C++ version was about twice as fast as the C# version.
The moral of the story is that C++ gives you the tools to write blazingly fast software, if you''re willing to do a lot of non-standard programming, and use a LOT of hacks.
C#, on the other hand, lets you write really really fast software right out of the gate, without resorting to any oddball shenanigans. But if you want to reach maximum possible performance, you will hit a wall sooner with C# than you would with C++. Additionally, a pIEce of software in C# will almost always have greater memory requirements than an equivalent C++ program.
There''s a summary of the story on Coding Horror, here:
http://blogs.msdn.com/ricom/archive/2005/05/10/performance-quiz-6-chinese
$False$
-english-dictionary-reader.ASPx
And you can read the whole play-by-play, here (follow all the links at the top of the page):
http://blogs.msdn.com/ricom/archive/2005/05/19/420158.ASPx
BenjiSmith
Saturday, December 08, 2007