From 5ce9a775a345cf458c0388d7288e246bb1b82bff Mon Sep 17 00:00:00 2001 From: "Vadim A. Misbakh-Soloviov" Date: Thu, 6 Apr 2023 03:10:22 +0700 Subject: [PATCH] Refactor Set._tostring. Fixes #61 __tostring convertation metatable function from the code imported from lua-set library has been reworked by the code, based on the idea, of the one, that was sugested by @GitSparTV in #61. The purpose of that refactoring is to reduce memory usage, caused by strings reallocation by string concatenation. (Table concatenation cheaper) Despite code should be pretty valid, and passes all tests, I think it needs to survive a bunch of real-life tests, but, unlikely, I have not enough spare time ATM. Please, test it and report, if any. Signed-off-by: Vadim A. Misbakh-Soloviov --- src/htmlparser/ElementNode.lua | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/htmlparser/ElementNode.lua b/src/htmlparser/ElementNode.lua index 0c39901..329043d 100644 --- a/src/htmlparser/ElementNode.lua +++ b/src/htmlparser/ElementNode.lua @@ -64,16 +64,27 @@ end -- String representation Set.mt.__tostring = function (set) - local s = "{" - local sep = "" + local list = {"{"} for k in pairs(set) do - s = s .. sep .. tostring(k) - sep = ", " + list[#list + 1] = tostring(k) + list[#list + 1] = ", " -- <= Theoretically, it should't be a problem because of string buffering. + -- Especially, as it allows to avoid string concatenation at all, and also allows to + -- avoid things like [1] + -- it looks like good idea to add separators this way. + -- But it needs to be tested on real-world examples with giant inputs. + -- If any (if it'd show that string buffering fails, and it is still leads huge RAM usage), + -- it can be downgraded to [1] or even string.format + -- + -- [1] = something like table.concat{"{",table.concat(list,","),"}"}, + -- end - return s .. "}" + list[#list] = "}" + + return table.concat(list) end + local ElementNode = {} ElementNode.mt = {__index = ElementNode} function ElementNode:new(index, nameortext, node, descend, openstart, openend)