ElementTree 和 BeautifulSoup 处理XML速度比较

文件:icd10cm_tabular_2019.xml
文件大小:8.7M

测试 1

将 XML 全部加在到内存,分别使用 ElementTree.fromstring 和 BeautifulSoup(字符串) 构建 10 次文档树,代码如下:

from bs4 import BeautifulSoup
from xml.etree import ElementTree
import time
from tqdm import trange

xml_path = "./icd10cm_tabular_2019.xml"
xml_content = None
with open(xml_path, "rb") as xml_file:
    xml_content = xml_file.read()

start_time = time.time()
for _ in trange(10):
    ElementTree.fromstring(xml_content)
print("ElementTree", round(time.time() - start_time, 2))

start_time = time.time()
for _ in trange(10):
    BeautifulSoup(xml_content, "lxml-xml")
print("BeautifulSoup lxml", round(time.time() - start_time, 2))

测试结果:

测试次数 耗时(秒) 平均耗时(秒)
ElementTree 10 8.53 0.8
BeautifulSoup lxml-xml 10 149.3 15

测试 2

不加载 XML 到内存,直接读文件,分别使用 ElementTree.parse 和 BeautifulSoup(文件流) 构建 10 次文档树,代码如下:

from bs4 import BeautifulSoup
from xml.etree import ElementTree
import time
from tqdm import trange

xml_path = "/Users/yangxiao/DATA/2019-ICD-10-CM/icd10cm_tabular_2019.xml"

start_time = time.time()
for _ in trange(10):
    with open(xml_path, "rb") as xml_file:
        ElementTree.parse(xml_file)
print("ElementTree", round(time.time() - start_time, 2))

start_time = time.time()
for _ in trange(10):
    with open(xml_path, "rb") as xml_file:
        BeautifulSoup(xml_file, "lxml-xml")
print("BeautifulSoup lxml", round(time.time() - start_time, 2))

测试结果:

测试次数 耗时(秒) 平均耗时(秒)
ElementTree 10 6.2 0.6
BeautifulSoup lxml-xml 10 105.56 10

结论:

ElementTree 明显快于 BeautifulSoup lxml-xml ,至少快 10 倍以上。
ElementTree.parse 速度快于 ElementTree.fromstring

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 人生苦短,我用Python。 起初,这篇文章是打算来写 XPath 的,可是后来一想,我需要的仅是 XPath 的...
    Moscow1147阅读 20,887评论 1 14
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,127评论 19 139
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,026评论 3 119
  • 当微风吹开,在你心泛起层层涟漪,你想起了什么? 一首歌,一个路口,一支圆珠笔,埋藏着诸多故事和深深情感的那些旧物,...
    D012希玛太原阅读 295评论 2 2
  • 六章 东未赶紧爬起来。 她住在亲王府的书苑里一个小院子里,书苑平时只有王爷来,除了日常的打扫基本没人看管,现在过了...
    lidio阅读 261评论 0 0