写点什么

探究 Openresty 中 ngx.re 与 Lua string.re 两种正则的选择

  • 2025-12-26
    北京
  • 本文字数:1436 字

    阅读完需:约 5 分钟

本文分享自天翼云开发者社区《探究Openresty中ngx.re与Lua string.re两种正则的选择》.作者:王****淋

0. 背景

openresty 中存在 2 套正则 API,即 ngx.re 与 lua 语言的 string 库,都可以实现正则匹配查找等功能,那么,这 2 个 API 有什么区别,又如何选择呢?

1. 性能测试

1.1 简单 loop 测试

a) 短字符串 &正则串

local http_range = 'bytes=10-65535'local string_re_p = '^bytes=([%d]*)%-([%d]*)$'local ngx_re_p    = '^bytes=([\\d]*)?\\-([\\d]*)$'local loop = 1000000
local t0 = get_t()for i = 1, loop do local _, _ = string_match(http_range, string_re_p)end
local t1 = get_t()for i = 1, loop do local m, err = ngx_re_match(http_range, ngx_re_p, "jo")endlocal t2 = get_t()
复制代码

Result: 0.247 vs. 0.32

b) 长字符串 &复杂正则串

local http_range = 'dsfds65465fwef bytes=12345757860-4465458586465 ewfsd65sd4fg65fsd'local string_re_p = '.*bytes=([%d]*)%-([%d]*) .+'local ngx_re_p    = '.*bytes=([\\d]*)?\\-([\\d]*) .+'local loop = 1000000
复制代码

Result: 1.16 vs. 0.526

由测试结果可以看出,对于字符串/正则规则越复杂,ngx-re 的性能是有优势的

1.2. 加入 jit 扰动

a) 对照组:ipairs 不破坏 jit (短串正则)

local http_range = 'bytes=10-65535'local string_re_p = '^bytes=([%d]*)%-([%d]*)$'local ngx_re_p    = '^bytes=([\\d]*)?\\-([\\d]*)$'local loop = 1000000
local t0 = get_t()for i = 1, loop do for k, v in ipairs({1,2}) do end local _, _ = string_match(http_range, string_re_p)end
local t1 = get_t()for i = 1, loop do for k, v in ipairs({1,2}) do end local m, err = ngx_re_match(http_range, ngx_re_p, "jo")endlocal t2 = get_t()
复制代码

jit-on: 0.369 - 0.326jit-off: 0.38 - 3.265

b) pairs 破坏 jit (短串正则)

local http_range = 'bytes=10-65535'local string_re_p = '^bytes=([%d]*)%-([%d]*)$'local ngx_re_p    = '^bytes=([\\d]*)?\\-([\\d]*)$'local loop = 1000000
local t0 = get_t()for i = 1, loop do for k, v in pairs({a=1,b=2}) do end local _, _ = string_match(http_range, string_re_p)end
local t1 = get_t()for i = 1, loop do for k, v in pairs({a=1,b=2}) do end local m, err = ngx_re_match(http_range, ngx_re_p, "jo")endlocal t2 = get_t()
复制代码

jit-off: 0.395 - 3.216jit-on: 0.394 - 1.04

c) pairs + 长复杂串

local http_range = 'dsfds65465fwef bytes=12345757860-4465458586465 ewfsd65sd4fg65fsd'local string_re_p = '.*bytes=([%d]*)%-([%d]*) .+'local ngx_re_p    = '.*bytes=([\\d]*)?\\-([\\d]*) .+'local loop = 1000000
复制代码

jit-on: 1.31 - 1.30jit-off: 1.307 - 2.94

超长串 + jit-on:

local http_range = 'dsfds6546vsdvsdfdsfsdfsdfwaasdasdasdas5fwef bytes=12354345345345757860-4465453453453453453453453458586465 ewfsd65safdknsalk;nlkasdnflksdajfhkldashjnfkl;ashfgjklahfg;jlsasd4fg65fsd'
复制代码

结果: 2.775 - 1.739

1.3 测试结果汇总

2. 结论

由测试结果可知:

1)在一般情况下,nginx-re 正则库更能适应复杂字符串与复杂正则规则的情况,一般情况下比较推荐使用 2)在极简单字符串的情况下,二者差别不大,string 正则稍带优势,可以按照方便的写法来写;

3)nginx-re 正则受 JIT 的影响更大,在关闭 jit 或使用 pairs 等情况下,可能会有拖累;

用户头像

还未添加个人签名 2022-02-22 加入

天翼云是中国电信倾力打造的云服务品牌,致力于成为领先的云计算服务提供商。提供云主机、CDN、云电脑、大数据及AI等全线产品和场景化解决方案。

评论

发布
暂无评论
探究Openresty中ngx.re与Lua string.re两种正则的选择_CDN_天翼云开发者社区_InfoQ写作社区