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 小时前
【从视频到数据集:焦糖玛奇朵的魔法工具使用说明】
人工智能·python·深度学习·学习·算法·yolo·音视频
潜创微科技5 小时前
IT6520:USB‑C 转 MIPI 芯片方案 4K@120Hz 高清显示
c语言·开发语言
yangshicong6 小时前
第11章:结构化输出与数据提取 —— 让 AI 直接返回你想要的数据格式
数据库·人工智能·redis·python·langchain·ai编程
言之。6 小时前
【Python】免费的中文 AI 配音方案
开发语言·人工智能·python
Warson_L6 小时前
python dict key详解
python
天天进步20156 小时前
Python全栈项目:从零手操一个高性能 API 网关
开发语言·python
Java面试题总结6 小时前
java高频面试题(2026最新)
java·开发语言·jvm·数据库·spring·缓存
安生生申7 小时前
使用pygame实现2048
开发语言·python·pygame
hh.h.8 小时前
CANN算子开发入门:从零开始写第一个Ascend C算子
c语言·开发语言·cann·c算子
AI科技星8 小时前
全域数学·第三部·数术几何部·平行网格卷 完整专著目录(含拓扑发展史+学科定位·终稿)
c语言·开发语言·网络·量子计算·agi