首頁  >  文章  >  後端開發  >  透過Parse和TryParse Try-Parse和Tester-Doer模式

透過Parse和TryParse Try-Parse和Tester-Doer模式

黄舟
黄舟原創
2017-03-04 10:36:381431瀏覽

Parse和TryParse

  DateTime中Parse(string s)和TryParse(string s, out datetime)都是用來將字元型的日期時間轉換為等效的System.DateTime。那麼,他們之間有沒有差別呢,除了函數的參數不同。先看下程式碼:

            string dateTimeStr = "";
            DateTime dt = DateTime.Parse(dateTimeStr);

  運行空字串,將其轉換為日期時間型,顯然不能轉化,並且Parse()會拋出一個異常:   System.FormatException: s 中不包含日期和時間的有效字串表示形式。但是,執行TryParse這個轉換方法:

            string dateTimeStr = "";       
            DateTime dt2; //dt2未经初始化,就被传递给函数TryParse()
            bool sucflag = DateTime.TryParse(dateTimeStr, out dt2);

  轉換首先是不拋出例外的,dt2被賦值為日期時間的最小值,sucflag為false。請參閱函數的註解:

當此方法傳回時,如果轉換成功,則包含與s 中包含的日期和時間等效的System.DateTime 值;如果轉換失敗,則為System.DateTime.MinValue。如果s 參數為 null,是空字串 (“”) 或不包含日期和時間的有效字串表示形式,則轉換失敗。 *該參數未經初始化即傳遞。這個函數是不會拋出任何異常的。

Try-Parse

  看到他們的不同後,進一步來講,parse()拋出異常必然影響性能,TryParse()未拋出任何異常,這是優化例外效能的設計模式,稱為Try-Parse Pattern。以下是微軟的官方解釋:

For extremely performance-sensitive APIs, an even faster pattern than the Tester-Doer Pattern described in the previous section should be used. The pattern calls for adjusting the member name to make a well-defined test case a part of the member semantics. For example, DateTime defines a Parse method that throws an exception if parsing of a string fails. It also defines a corresponding parse, but returns false if parsing is unsuccessful and returns the result of a successful parsing using an out parameter.

Tester-Doer

ry ##T#Tester-Doer
##ry-Par#T
#se模式時,微軟提出了另一個模式:

Tester-Doer模式

,什麼是Tester-Doer模式呢? 函數中寫入異常,會降低效能,微軟給了這種模式來減少異常所帶來的副作用。

 

  如下程式碼:

ICollection<int> numbers = 省略获取数据的逻辑
numbers.Add(1);//Add此处不做可写性检查

  以上缺陷:假如集合是唯讀的,方法Add會拋出例外。呼叫這個方法的地方會經常拋出異常,因此會影響系統的效能。為了避免這個設計缺陷,微軟提出: Sometimes performance of an exception-throwing member can be improved by breaking the member into two.

  將Add()分解為:

ICollection<int> numbers = 省略获取数据的逻辑if(!numbers.IsReadOnly) //Tester{
    numbers.Add(1); //Doer}
#  將Add()分解為:rrreee  Tester-Do Testerer  Testerer  Testerer  Testerer  Testerer  Testerer  Testerer模式總結:

The member used to
test a condition

, which in our example is the property

IsReadOnly

, is referred to as the tester. The member used to perform a
potentially throwing operation

, the Add method in our example, is referred to as the doer.


#   分解後,先做唯讀性檢測,這樣會減少Add拋出只讀性異常的次數,提升效能。


總結

  Try-Parse Pattern和Tester-Doer模式是兩種替代拋異常的最佳化方式,起到優化設計效能的作用。 ###### 以上就是透過Parse和TryParse Try-Parse和Tester-Doer模式 的內容,更多相關內容請關注PHP中文網(www.php.cn)! ################
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn