Lua Memory __lua Memory

Source: Internet
Author: User
Lua Memory leaks

First 1th, the memory leaks in Lua are essentially different from what we call the memory leaks in C + +. There is a garbage collection mechanism (GC) in Lua, so there is no memory leak in theory. When it does GC, it scans all the objects from the root, and if there is a reference to the object somewhere, the object memory is not collect, and the object is not GC. So memory leaks in Lua are those that are not already in use, but are still externally referenced objects.

[plain] view Plain copy--the object that should be declared as local in the function forgot to add the local local function test () TestTable = {}-this Testtabel will be stored in <span style= "Background-color:rgb (255, 255, 0);"        > Global Table _g</span>, there will always be a table leak because the object still has references in the GC.        The local MT = {}--mt adds a local decoration, and when the function is called, the reference ceases to exist and the GC is reclaimed. Setmetatable (testtable, MT) end

Here are some common error-referencing scenarios:
1. Local variables should be entered into global space or module space (forget to write locals) if
This is a table/function/udata and other type of variable, unfortunately, this variable will not
is correctly GC----unless you explicitly release it again. It's very easy to make a mistake and have been wondering why
The LUA variable is not the default local. Of course this topic will spark another controversy.
Local function Test_user (ID)
Userobj = get_user_by_id (ID)--there will always be a player object leaking
Print ("Only Test", Userobj:get_name ())
End

2. Whether the lua_ref of the C + + section call has normal Lua_unref release. Pass
Debug.getregistry () can refer to these ref.

3. Other kinds of actual bugs caused by leakage.

Workaround:

You can create a weak table that throws all of the objects you have created that can be called resources, including but not limited to "combat objects, players, NPC, objects, scenes, emails", and so on, into this table. When you know the player
The line has been removed, the battle has been destroyed, but there is also this variable in the weak table after successive forced full GC, which proves that the reference to this variable is not completely released.

It's easy to know if there's a leak, it's not easy to get it out completely. Yes, where is it? In the beginning of this project is also first found that a NPC leakage, and then go to the code to see where it is written incorrectly. This approach is extremely inefficient and basically does not find any problems. Use the present scheme at a later time: traverse all table, metatable, Funciton ' s upvalue, function ' env, Registentry (LUA_REF) from the _g depth. All the references currently known must exist in these spaces, and the "lost references" must be found after the traversal is complete. This way you can do everything at the script level, even if you can check it online in the operating environment, the speed of the traversal is very fast, but the memory overhead is very large (:, you can consider one side to traverse the GC, of course, remember to avoid repeated search. After you apply this scenario, this project resolves all the leak issues in the script.


Detection Principle

There are five of objects in Lua that support the garbage collection mechanism:string,table,function,full userdata,thread. and their references are directly or indirectly saved to :lua_state objects, _g Global tables, registry registry, GLOBAL_STATE->MT.

In the script: the Lua script that runs is lua_state itself. _g is the _g global table. Registry tables can be obtained by debug.getregistry. GLOBAL_MT can be obtained by debug.getmetatable. So we can implement the memory leak detection module at the script level.

In search of need to pay attention to several points: Table additional search metatable, if metatable in the __mode value of "K", "V" or "kv" need special treatment (in addition to the note); Function additional search enviroment, also a table; Extra Search upvalues, this can be any type. Because the UserData can not be modified at the script level, so search his MetaTable thread object is Coroutine object, in the script will not create more than one coroutine, so not search for it in scripts. If required, get the thread function of it, and then follow the 2nd step. Search Flowchart (_g table)

Before detecting the leak, search all the objects, save the initial memory state, perform several GC operations after the program executes, and then conduct a search, comparing the results of two times, the more out of those may be memory leaks.

The __mode assignment is "K", "V" or "kv", which means that the key or value or key value stored in it is a weak reference state. If all references to an object are weak references, the object is also reclaimed by GC, so the entry for the object in the corresponding weak table is missing.

So we can use another kind of implementation: to throw all the resource objects created by the user into the weak table, forcing the GC after running the program and then looking at the weak table, if that object is still in the table, means that the object also has an external reference (a relatively weak reference we call it a strong reference), The resource has not been dropped by GC, so we can say that this object is likely to be a memory leak. (In order to discover a memory leak, we can create a global weak reference table, make its key a weak reference, and then, every time we create a potentially leaking object, put it in the table as a key,value and usually I use the current time.) Because of the nature of the weak reference, if the other references disappear, the reference to the object in the weak reference table disappears (becomes nil), whereas the reference to the object in the weak reference table persists as long as any other reference exists. Depending on this feature, when the program has run over the logic of releasing the object, if there is a reference to the object in the table, then the object must be leaked. )

Lua garbage collection algorithm

The so-called "Mark and Sweep" algorithm used by LUA's GC algorithm. Simply understood, the algorithm divides the GC into two phases, one marked (Mark) phase, which marks all the objects referenced in the system , and in the cleanup (sweep) phase, deletes data that is not marked in the mark phase.

In Lua, you use several colors to differentiate between different nodes:

White: Black indicates a node that has not been marked

Gray: Grey indicates a node that has been marked, but the node associated with it has not been marked.

Black: Both this node and the node with which it is associated have been flagged by the scan. Typically, there are data types associated with data, including Table,upvalue. Garbage collector functions

The CollectGarbage function provides a number of features: stop garbage collection , reboot garbage collection , force a recycle loop , force a one-step garbage collection , and get the memory that Lua occupies , and two parameters that affect the frequency and pace of garbage collection . CollectGarbage (Opt,[,arg])

"Stop"

Stop the garbage collector if it's running.

"Restart"

If the garbage collector has stopped, it will be restarted.

"Collect"

Perform a full garbage collection cycle. Perform this action by default

"Count"

Returns the amount of memory used in the current LUA (in kilobytes)

"Step"

Step through a garbage collection. The step size is specified by the parameter arg (a large value requires more than a step to complete), and if you want to specify the step size exactly, you need to experiment multiple times to achieve the best results. Returns true if the step completes a collection loop

"Setpause"

Sets the value of the arg/100 as the time of the tentative collection, and returns the value before the setting. Default is 200

Controls how long the collector waits before starting a new collection cycle. As the number increases, the collector's work is less active. A value less than 1 means that the collector will not wait at the beginning of the new cycle. A value of 2 means that a new cycle is opened when the total amount of memory used is twice times the original.

"Setstepmul"

Sets the value of the arg/100 as the increment of the step (that is, the new step = Old step *arg/100), and returns the value before the setting. Default is 200

Controls the speed at which the collector works, which is a speed relative to the memory allocation. A larger number will cause the collector to work more aggressively at the same time, and also to increase the size of the collection at each step. A value less than 1 causes the collector to work very slowly and may cause the collector to never end the current cycle. The default value is 200%, which means that the collector will run at twice times the speed of the memory allocator.

[Plain]  View plain  copy function test1 ()        collectgarbage ("collect")-- In order to have a clean environment, first collect the garbage can collect        collectgarbage ()--in order to ensure the relatively clean memory collection, and memory stability, to perform multiple collection         print ("Now,lua memory is:", CollectGarbage ("Count")  -->205.7158203125 kb        local colen = {} --is now a local variable         for i=1,5000 do           table.insert ( colen,{})        end       print ("Now,lua memory is:", CollectGarbage ("Count")-->860.4111328125 kb       --creates 5,000 table, Memory added 655 kb   end      function collect1 ()         print ("Now,lua memory is:", CollectGarbage ("Count"))-->608.060546875 kb        collectgarBage ()        collectgarbage ()        print ("Now, Lua memory is: ", CollectGarbage (" Count ")-->204.8408203125 kb       -- Finally with a first only difference 1kb   end      function test2 ()         CollectGarbage ("collect")--to have a clean environment, first collect the garbage can be collected        collectgarbage () To ensure the relatively clean collection of memory, and the stability of the memory, to perform multiple collection        print ("Now,lua memory is:", CollectGarbage ("Count"))  -->205.7158203125 KB       colen = {} --is now a global variable        for i=1,5000 do            table.insert (colen,{})        end        Print ("Now,lua memory is:", CollectGarbage ("Count"))-->619.826171875 kb       -- Create 5,000 table, memory increased 414&NBSP;KBThese increased memory, because it has been placed in the global function, is never a chance to be recycled to the!   end      function collect2 ()        print ("Now,lua memory is:", CollectGarbage ("Count"))-->596.7822265625 kb       collectgarbage ()        collectgarbage ()         collectgarbage ()        print ("Now,lua memory is:", CollectGarbage (" Count ")-->489.189453125 kb       --last memory increased by 284KB (489-205)    end   

The garbage collector has two parameters to control its rhythm:

The first parameter, called the pause time, is how long the control collector waits before it completes a recycle and starts the next recycle;

The second parameter, called the stepping factor, controls how much content the collector reclaims per step. Roughly speaking, the smaller the pause time, the greater the stepping coefficient, the faster the garbage collection. The impact of these parameters on the overall performance of the program is unpredictable, and the faster garbage collector obviously wastes more CPU cycles, but it lowers the amount of memory consumed by the program and may reduce paging. Only careful testing can give you the best parameter values. [Transferred from]http://www.2cto.com/kf/201502/377646.html

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------

Weak reference table for the LUA tutorial

This time I want to introduce a little bit, just one--weak reference table

1. Intelligence Beyond human wisdom-defects in automatic memory management

As we all know, Lua is equipped with automatic memory management

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.