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个英文字母,而其他方法要处理所有字符(包括特殊符号等等),这样其他方法处理的字符数量比正则这种方法要多
相关推荐
深度学习lover14 小时前
<数据集>yolo 瓜果蔬菜识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·瓜果蔬菜识别
我能坚持多久14 小时前
STL详解——list的介绍以及功能展示
开发语言·c++
2401_8676239814 小时前
JavaScript中Number-isSafeInteger的校验逻辑
jvm·数据库·python
Yu_Mao_Cat14 小时前
小工具备份
python
Brilliantwxx14 小时前
【C++】 继承与多态(上)
开发语言·c++·笔记·算法
ch.ju14 小时前
Java程序设计(第3版)第四章——静态部分
java·开发语言
ZHOUPUYU14 小时前
PHP 开发实战:从零搭建一个高性能的 RESTful API 服务
运维·开发语言·后端·html·php
不负岁月无痕14 小时前
STL -- C++ string 类 模拟实现
java·开发语言·c++
阿_旭14 小时前
基于YOLO26深度学习的【咖啡果实成熟度检测与计数系统】【python源码+Pyqt5界面+数据集+训练代码】
人工智能·python·深度学习·咖啡果实检测
Anastasiozzzz14 小时前
万字深度实战!AI Agent 接入万物的底层密码:MCP 协议传输机制与开发指南(下篇)
java·开发语言·数据库·人工智能·ai·架构