给定一个字符串,统计字符串中大写字符个数,有如下三种方法:
python
# method1
s1 = len(re.findall(r'[A-Z]',content))
# method2
s2 = sum(1 for c in content if c.isupper())
# method3
s3 = 0
for c in content:
if c.isupper()==True:
s3+=1
经过多次实测后,方法1是最快的,方法3是最慢的。下面是其中某一次的实际时间消耗:
(method1) upper char count by re:0.11256217956542969s
(method2) upper char count by for-sum:0.36724019050598145s
(method3) upper char count by for-loop:0.5580060482025146s
改为统计字符串中大写字符个数和小写字符个数后:
python
s11 = len(re.findall(r'[A-Z]',content))
s12 = len(re.findall(r'[a-z]',content))
s21 = sum(1 for c in content if c.isupper())
s22 = sum(1 for c in content if c.isupper())
s3 = 0
s4 = 0
for c in content:
if c.isupper()==True:
s3+=1
else:
s4+=1
性能也满足上面的规律:
upper char count by re:0.40007758140563965s
upper char count by for-sum:0.6471347808837891s
upper char count by for-loop:0.918128252029419s
原因分析:
- 正则表达式在匹配上是有算法优化过的
- 正则只处理26个英文字母,而其他方法要处理所有字符(包括特殊符号等等),这样其他方法处理的字符数量比正则这种方法要多