python统计字符串中大小写字符个数的性能实测与分析

给定一个字符串,统计字符串中大写字符个数,有如下三种方法:

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个英文字母,而其他方法要处理所有字符(包括特殊符号等等),这样其他方法处理的字符数量比正则这种方法要多
相关推荐
专注VB编程开发20年5 分钟前
javascript的类,ES6模块写法在VSCODE中智能提示
开发语言·javascript·vscode
郭庆汝5 小时前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
黄雪超7 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice7 小时前
对象的finalization机制Test
java·开发语言·jvm
思则变8 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
lijingguang8 小时前
在C#中根据URL下载文件并保存到本地,可以使用以下方法(推荐使用现代异步方式)
开发语言·c#
漫谈网络8 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
¥-oriented8 小时前
【C#中路径相关的概念】
开发语言·c#
CoderCodingNo8 小时前
【GESP】C++四级考试大纲知识点梳理, (7) 排序算法基本概念
开发语言·c++·排序算法
恋猫de小郭9 小时前
Meta 宣布加入 Kotlin 基金会,将为 Kotlin 和 Android 生态提供全新支持
android·开发语言·ios·kotlin