PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

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

黄舟
黄舟 原创
2017-03-04 10:36:38 1199浏览

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 TryParse method that attempts to parse, but returns false if parsing is unsuccessful and returns the result of a successful parsing using an out parameter.

Tester-Doer

  在解释Try-Parse模式时,微软提出了另外一种模式: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}

  Tester-Doer模式 总结:

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中文网(m.sbmmt.com)!


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。