From 34e73da4243f6535d12e8b76b556e88d7addea8a Mon Sep 17 00:00:00 2001 From: Lars Mueller Date: Fri, 2 May 2025 14:52:43 +0200 Subject: [PATCH] Optimize appending to tables in `core.serialize` and `dump` --- builtin/common/misc_helpers.lua | 12 ++++++++++-- builtin/common/serialize.lua | 8 ++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/builtin/common/misc_helpers.lua b/builtin/common/misc_helpers.lua index 77847eb91..a1f352afa 100644 --- a/builtin/common/misc_helpers.lua +++ b/builtin/common/misc_helpers.lua @@ -122,8 +122,16 @@ function dump(value, indent) local newline = indent == "" and "" or "\n" local rope = {} - local function write(str) - table.insert(rope, str) + local write + do + -- Keeping the length of the table as a local variable is *much* + -- faster than invoking the length operator. + -- See https://gitspartv.github.io/LuaJIT-Benchmarks/#test12. + local i = 0 + function write(str) + i = i + 1 + rope[i] = str + end end local n_refs = {} diff --git a/builtin/common/serialize.lua b/builtin/common/serialize.lua index 8f463d978..9ebece6d0 100644 --- a/builtin/common/serialize.lua +++ b/builtin/common/serialize.lua @@ -218,9 +218,13 @@ function core.serialize(value) core.log("deprecated", "Support for dumping functions in `core.serialize` is deprecated.") end local rope = {} + -- Keeping the length of the table as a local variable is *much* + -- faster than invoking the length operator. + -- See https://gitspartv.github.io/LuaJIT-Benchmarks/#test12. + local i = 0 serialize(value, function(text) - -- Faster than table.insert(rope, text) on PUC Lua 5.1 - rope[#rope + 1] = text + i = i + 1 + rope[i] = text end) return table_concat(rope) end