以前看過文章說MarshalByRefObject 會造成效能的損失,我比較相信自己,所以親自測試了一下,下面是程式碼:
測試程式碼
using System;
using System.Diagnostics;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
Stopwatch watch = new Stopwatch();
watch.Start();
B b = new B();
for (int i = 0; i < 100000000; i++) {
b.Add(3, 5);
}
watch.Stop();
Console.WriteLine("B 花費時間:" + watch.ElapsedMilliseconds.ToString());
watch.Reset();
watch.Start();
A a = new A();
for (int i = 0; i < 100000000; i++) {
a.Add(3, 5);
}
watch.Stop();
Console.WriteLine("A MarshalByRefObject 花費時間:" + watch.ElapsedMilliseconds.ToString());
watch.Reset();
//=======================
watch.Start();
a = new A();
for (int i = 0; i < 100000000; i++) {
a.Add(3, 5);
}
watch.Stop();
Console.WriteLine("A MarshalByRefObject 花費時間:" + watch.ElapsedMilliseconds.ToString());
watch.Reset();
watch.Start();
b = new B();
for (int i = 0; i < 100000000; i++) {
b.Add(3, 5);
}
watch.Stop();
Console.WriteLine("B 花費時間:" + watch.ElapsedMilliseconds.ToString());
watch.Reset();
Console.Read();
}
}
class A : MarshalByRefObject {
public int Add(int a, int b) {
return a + b;
}
}
class B {
public int Add(int a, int b) {
return a + b;
}
}
}
using System;
using System.Diagnostics;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
Stopwatch watch = new Stopwatch();
watch.Start();
B b = new B();
for (int i = 0; i < 100000000; i++) {
b.Add(3, 5);
}
watch.Stop();
Console.WriteLine("B 花費時間:" + watch.ElapsedMilliseconds.ToString());
watch.Reset();
watch.Start();
A a = new A();
for (int i = 0; i < 100000000; i++) {
a.Add(3, 5);
}
watch.Stop();
Console.WriteLine("A MarshalByRefObject 花費時間:" + watch.ElapsedMilliseconds.ToString());
watch.Reset();
//=======================
watch.Start();
a = new A();
for (int i = 0; i < 100000000; i++) {
a.Add(3, 5);
}
watch.Stop();
Console.WriteLine("A MarshalByRefObject 花費時間:" + watch.ElapsedMilliseconds.ToString());
watch.Reset();
watch.Start();
b = new B();
for (int i = 0; i < 100000000; i++) {
b.Add(3, 5);
}
watch.Stop();
Console.WriteLine("B 花費時間:" + watch.ElapsedMilliseconds.ToString());
watch.Reset();
Console.Read();
}
}
class A : MarshalByRefObject {
public int Add(int a, int b) {
return a + b;
}
}
class B {
public int Add(int a, int b) {
return a + b;
}
}
}
測試的結果是:
B 花費時間:55
A MarshalByRefObject 花費時間:957
A MarshalByRefObject 花費時間:972
B 花費時間:56
總結:像這樣在本地環境下,效能仍然損失了近17.4倍。當然,此17被不能簡單的理解為你的應用就慢了17倍,這裡僅表示發起呼叫損失了17倍。
注意:
執行測試程式時,首先選擇Release,然後選擇專案的屬性=》Build(編譯)=》高階=》除錯資訊 設定為none。
然後選擇:除錯=》不除錯執行。或找到exe直接雙擊執行。