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个英文字母,而其他方法要处理所有字符(包括特殊符号等等),这样其他方法处理的字符数量比正则这种方法要多
相关推荐
报错小能手5 小时前
计算机网络自顶向下方法16——应用层 因特网视频 HTTP流和DASH
开发语言·计算机网络·php
消失的旧时光-19435 小时前
Kotlin 协程实践:深入理解 SupervisorJob、CoroutineScope、Dispatcher 与取消机制
android·开发语言·kotlin
错把套路当深情5 小时前
Kotlin List扩展函数使用指南
开发语言·kotlin·list
草莓熊Lotso5 小时前
《算法闯关指南:优选算法--前缀和》--27.寻找数组的中心下标,28.除自身以外数组的乘积
开发语言·c++·算法·rpc
想不明白的过度思考者5 小时前
Rust——Trait 定义与实现:从抽象到实践的深度解析
开发语言·后端·rust
凤年徐6 小时前
Rust async/await 语法糖的展开原理:从表象到本质
开发语言·后端·rust
CLubiy6 小时前
【研究生随笔】Pytorch中的卷积神经网络(2)
人工智能·pytorch·python·深度学习·cnn·卷积神经网络·池化
AnalogElectronic6 小时前
vue3 实现记事本手机版01
开发语言·javascript·ecmascript
Cx330❀6 小时前
《C++ 继承》三大面向对象编程——继承:派生类构造、多继承、菱形虚拟继承概要
开发语言·c++
晨陌y6 小时前
从 “不会” 到 “会写”:Rust 入门基础实战,用一个小项目串完所有核心基础
开发语言·后端·rust