16进制描述的字符串转字符串效率问题

133 views
Skip to first unread message

tylerpiece

unread,
Apr 12, 2017, 3:37:43 AM4/12/17
to openresty
text是一串16进制表示的字符串,现在想把他转为普通字符串,代码如下。运行后,用火焰图抓,发现pcall那一句的CPU占用率很高
不知道有好的写法没有

   
 local str_t ={}
    for var = 1,#text,2 do
        local hex = string.sub(text,var,var+1)
        local x = nil
        if pcall(function (hex) x = string.char(string.format("%d","0x"..hex)) end, hex) then
                str_t[#str_t + 1] = x
        else
            ngx.log(ngx.ERR,"uri args decrypt transform hex error")
            return
        end
    end


 

Ming

unread,
Apr 12, 2017, 5:22:51 AM4/12/17
to open...@googlegroups.com
可以把 Lua land 火焰图贴出来看看,用这个工具:https://github.com/openresty/stapxx#lj-lua-stacks

我猜测 lj_str_new 和 lj_gc_step_jit 可能比较高。如果你的字符串很长,rehashtab 和 lj_tab_resize 也会很高。

1、你可以提前对 text 的字符进行 format,放到一个数组里面预置好。而不是用 string.format("%d","0x"..hex) 重复的 format。
2、同理,提前 string.char 到一个数组里面预制好,避免不停的函数调用,以及生成大量的字符。
3、如果你使用的是 LuaJIT 2.1 beta2 的版本,你可以 table.new 来生成数组,而不是 str_t = {} 这种方式。



 

--
--
邮件来自列表“openresty”,专用于技术讨论!
订阅: 请发空白邮件到 openresty+subscribe@googlegroups.com
发言: 请发邮件到 open...@googlegroups.com
退订: 请发邮件至 openresty+unsubscribe@googlegroups.com
归档: http://groups.google.com/group/openresty
官网: http://openresty.org/
仓库: https://github.com/agentzh/ngx_openresty
教程: http://openresty.org/download/agentzh-nginx-tutorials-zhcn.html

tylerpiece

unread,
Apr 12, 2017, 5:47:45 AM4/12/17
to open...@googlegroups.com
非常感谢。确实是lj_str_new占用了很多。我准备根据你的建议来尝试优化下代码。





订阅: 请发空白邮件到 openresty+subs...@googlegroups.com
发言: 请发邮件到 open...@googlegroups.com
退订: 请发邮件至 openresty+unsub...@googlegroups.com
reg.svg
Reply all
Reply to author
Forward
0 new messages