天天看點

性能測試筆記

想比較 as , is , typeof , GetType , 強制類型轉換 這幾個哪個性能更好。

以下是測試代碼:

<col>

單元測試下Debug

第一次

 

第二次

第三次

平均

As:142

As:147

As:160

As:150

Is:157

Is:152

Is:177

Is:162

(string):146

(string):147

(string):165

(string):153

typeof:611

typeof:616

typeof:687

typeof:637

GetType:314

GetType:313

GetType:353

GetType:327

單元測試下Release

As:21

As:20

Is:20

(string):98

typeof:20

GetType:333

GetType:348

GetType:339

Console程式Debug

As:183

As:184

Is:295

Is:411

Is:334

(string):231

(string):177

(string):241

(string):216

typeof:278

typeof:216

typeof:213

typeof:236

GetType:477

GetType:430

GetType:424

GetType:443

Console程式Release

As:11

Is:6

(string):45

typeof:7

typeof:6

GetType:6

GetType:7

單元測試下,性能是不準的。

Release 下性能 比較:  is = typeof 高于 GetType 高于 As  高于 強制類型轉換。

 ----------------------------------------------------------

持續對以上結果表示懷疑,增加循環次數。

性能測試筆記
性能測試筆記

View Code

結果:

typeof: 45

GetType: 44

object.Equals: 1620

default: 44

String______________

new string: 45

String.Length: 45

string.IsNullOrEmpty: 900

As: 44

Is: 46

(string): 391

ToString: 53567

AsString: 146645

______________String

類型轉換______________

DateTime: 35750

Guid: 69539

AsDecimal: 72932

AsFloat: 289442

______________類型轉換

Reflect: 71428

As  的性能略高于 Is , 但 判等的性能卻是出忽意料的差。

再加入 == 判定測試 和 a.Equals 的判定測試:

typeof: 58

GetType: 50

object.Equals: 1736

==: 49

a.Equals: 2420

default: 50

new string: 50

String.Length: 50

string.IsNullOrEmpty: 969

As: 50

Is: 50

(string): 441

ToString: 52179

AsString: 139356

DateTime: 35400

Guid: 69725

AsDecimal: 82086

AsFloat: 321944

Reflect: 63618

檢視源碼:

性能測試筆記

  作者:NewSea   

  如無特别标記說明,均為NewSea原創,版權私有,翻載必糾。歡迎交流,轉載,但要在頁面明顯位置給出原文連接配接。謝謝。

繼續閱讀