如何管理大字符串

在我对ESP8266的最近测试中,我遇到了一个内存限制。

我有一个简单的http服务器,用于提供周围ESP8266可用AP的json。

function incoming_connection(conn, payload)
 conn:send('HTTP/1.1 200 OK\n')
 conn:send('Content-Type: application/json\n\n')
 conn:send(tableToJson1(currentAPs))
end

当我在家里,在巴黎时,AP列表可能很长,然后我达到了有效载荷最大尺寸。

为了避免这种内存恐慌,我想将我的json分成几个块,然后逐个发送。

我写了这个:

function splitString(str, maxlen)
  local t = {}
  for i=1, math.ceil(string.len(str)/maxlen) do
    t[i] = string.sub(str, (i-1)*maxlen+1, i*maxlen)
  end
  collectgarbage()
  return t
end

然后尝试使用此函数进行测试:

function genstr(len)
  local s=""
  for i=1,len do
    s=s.."x"
  end
  return s
end
for k,v in pairs(splitString(genstr(2000))) do print(v) end

一些测试结果:

生成字符串的长度+字符串块的长度+结果
1500+100+OK
1500+200+OK
2000+100+显示8行后崩溃
2000+200+显示4行后崩溃

似乎我在1500字节左右达到了内存限制。

您有什么建议来超过此限制吗?

点赞
用户1009479
用户1009479

问题可能出现在 genstr 而不是 splitString 中。

在 Lua 中,字符串是不可变的,在 genstr 中,每次 s=s.."x" 循环中都会生成一个新字符串。

  for i=1,len do
    s=s.."x"
  end

相反,你可以使用内置的 string.rep (或者对于更复杂的情况,使用 table.concat)生成测试字符串。

2015-10-12 11:34:07