7

I'd like to find out how much memory a Lua table is using - without iterating through the table contents and counting up the usage. Is there a Lua 5.1 function or 3rd party library that could help with this.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user295625
  • 73
  • 1
  • 1
  • 3

4 Answers4

10

You can monitor the memory usage of Lua by calling collectgarbage("count") or gcinfo() in the appropriate locations throughout the code (e.g. before and after insert operations). There's no trivial way to get the size of a table.

lukas.pukenis
  • 13,057
  • 12
  • 47
  • 81
deorst
  • 761
  • 3
  • 13
2

There is no function for this task. Why do you want to do this? What are you trying to achieve?

lhf
  • 70,581
  • 9
  • 108
  • 149
  • I'm working with a lua app that is consuming a lot of memory - and ultimately eating up the available RAM. Frankly, it's a design flaw and I can see in the problem areas in the source code. A rewrite/rethink is needed but I can't get started on that for a month. In the interim I'm looking for a quick fix to get a customer up and running again. I figured a more detailed breakdown of the memory usage would help me to decide which part(s) to change/workaround now. – user295625 Mar 18 '10 at 11:25
  • Have you tried tweaking garbage collection or using the emergency garbage collection patch? http://lua-users.org/wiki/EmergencyGarbageCollector It's quite stable, and also rather useful for even more embedded situations (64k SRAM on a microcontroller :-) Lua 5.2 pre-release versions also has an EGC, which is not the above patch, but should provide similar functionality. Are you actually using up all available memory with objects that are still in use? As you might find noted on the Lua list links in one of the other replies, Lua allows you to define whatever you want as a memory allocator. – James Snyder Mar 21 '10 at 03:41
  • this would be useful to help identify existence of leaks _in the lua script_. – david van brink Aug 12 '23 at 19:43
1

Wouldn't something like this or this help?

2016 Update: see also: http://www.lua.org/wshop15/Musa2.pdf

Alexander Gladysh
  • 39,865
  • 32
  • 103
  • 160
1

You could do something like this:

local pre = collectgarbage("count")
local table = {1, 2, 3, 4, 5}
local aft = collectgarbage("count")

local probablyTableSize = aft - pre
print(probablyTableSize)

Do note though, I am not too sure if this would be accurate outside of plain testing environments with a lot of things going on in the background. There is a slight chance that more memory was added/removed when we were declaring the table variable.

This may be redundant, but what you could do in that case would be to get the mean or the median of multiple attempts and see what happens.

TrèsAbhi
  • 68
  • 1
  • 9