CollectGarbage_The Collector

CollectGarbage_The CollectorCollectgarbage- ItdoeswhatitsaysitdoesDefinitioncollectgarbage([opt[,arg]])Thisfunctionisagenericinterfacetothegarbagecollector.Itperformsdifferentfunctionsaccording

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全家桶1年46,售后保障稳定

Collectgarbage – It does what it says it does

Definition

collectgarbage ([opt [, arg]])This function is a generic interface to the garbage collector. It performs different functions according to its first argument, opt:

  • “collect”: performs a full garbage-collection cycle. This is the default option.
  • “stop”: stops the garbage collector.
  • “restart”: restarts the garbage collector.
  • “count”: returns the total memory in use by Lua (in Kbytes).
  • “step”: performs a garbage-collection step. The step “size” is controlled by arg (larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value of arg. Returns true if the step finished a collection cycle.
  • “setpause”: sets arg as the new value for the pause of the collector. Returns the previous value for pause.
  • “setstepmul”: sets arg as the new value for the step multiplier of the collector. Returns the previous value for step.

For now, let’s just focus on the collect and count options.

Let’s look at a few examples

We’ll just try a few things out and see how they’ll run. Remember to click on the green button to see what acctually happens with the code.

Counting memory usage

To find the number of kilobytes currently in use by Lua, you can simply make a call with count.

1 print(collectgarbage("count")*1024)
2 a = "123"
3 print(collectgarbage("count")*1024)

What you see in the console is the memory usage before and after the assignment. You should see around \sim 21 – 22 bytes of memory used up by the assignment.

Forcing a full run of garbage collection

If we don’t specify an option, then Lua will perform a full collection

1 a = {
1,2,3}
2 a = nil
3 collectgarbage()

Found in the wild

To top it off, let’s look at some real world uses of collectgarbage.

Keeping track of memory usage

This is usually used during “profiling”, or checking the performance of your code. For the most part, keeping an eye on the memory usage may ensure that your code doesn’t go through some crazy mood cycle and decide to blow up on you at the most unexpected time. For the most part however, since Lua still automates collection and keeps track of every by itself, this is unnecessary.

When you create new objects instead of reusing older ones

Since the notion of memory seems like such a faraway concept in Lua, it is easy to often forget that creating new objects take up memory, and certain patterns of coding could end up using up memory and then immediately discarding it faster than Lua can reclaim the wasted space.

In one extremely contrived example, there’s a good analogy of that new kid at school who wants to pretend to be cool, so he drew a mustache on his face on his first day; in the marginally more mature world of programming, that new kid is the guy who just read the wikipedia article on “lambda-calculus” (haven’t heard of it yet? don’t worry, you’re not going to need it unless you want to be a theoretical computer scientist) and decides to rub his knowledge in on /r/learnprogramming.

Now, this guy wants to implement the number one million through one million function calls to stay true to his “hip”ness, so he decides to write the following function to do just that. (Don’t worry about a function calling itself, it usually does what you think it will do)

01 function f(y)
02     local x = y + 1
03     return function() return f(x) end
04 end
05  
06 collectgarbage('stop')
07 g = f(0)
08 for i=1,10000 do
09     g = g()
10 end
11  
12 print(collectgarbage('count'))
13 collectgarbage('restart')

(Note: be very cautious when running that code, it does take a fair bit of memory and time so it may freeze your browser up)

It might not make sense that just calling functions and immediately discarding them could incur up so much memory usage, but just for the sake of illustration, just pretend that each function is equivalent to a table and that each function call is equivalent to looking up some element within that table that also turns out to be a table. In this case, we only care about the millionth inner nested table and none of the other ones; but in order to get to that inner nested table, we still need to keep the other tables in memory. Now to make matters worse, in the case of functions, we’re creating those tables on the go.

Anyways, do another collection and see how much memory was freed.

id=”dsq-2″ data-disqus-uid=”2″ allowtransparency=”true” frameborder=”0″ scrolling=”no” tabindex=”0″ title=”Disqus” width=”100%” src=”http://disqus.com/embed/comments/?base=default&disqus_version=28061892&f=theluatutorial&t_i=assert&t_u=http%3A%2F%2Fluatut.com%2Fcollectgarbage.html&t_d=The.Lua.Tutorial%20%C2%BB%20collectgarbage()&t_t=The.Lua.Tutorial%20%C2%BB%20collectgarbage()&s_o=default#2″ horizontalscrolling=”no” verticalscrolling=”no” style=”margin: 0px; padding: 0px; outline: 0px; vertical-align: baseline; background-color: transparent; width: 620px; border-style: none !important; overflow: hidden !important; height: 75px !important;”>

Disqus seems to be taking longer than usual. Reload?

本文出自:http://luatut.com/collectgarbage.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/213486.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • matlab griddata nan,请教Matlab的griddata的用法

    matlab griddata nan,请教Matlab的griddata的用法请教Matlab的griddata的用法以下文字资料是由(历史新知网www.lishixinzhi.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!请教Matlab的griddata的用法MATLAB散乱点插值函式griddata函式语法:ZI=griddata(x,y,z,XI,YI)[XI,YI,ZI]=griddata(x,y,z,XI,YI)[…]=gri…

  • Java转golang_json数组转json对象

    Java转golang_json数组转json对象1.omitempty如果对应的字段没有值,则忽略,有,则不会略2.-永久忽略代码:packagemainimport(“encoding/json””fmt”)typePersonstruct{Namestring`json:”name”`Ageint`json:”age”`Addrstring`json:”addr,omitempty”`//不存在,则忽略.存在则,不忽略}typeAnimalstru..

  • 网络安全之KALI渗透手机、获取目标的精确位置

    网络安全之KALI渗透手机、获取目标的精确位置

  • XXE漏洞以及Blind XXE总结「建议收藏」

    XXE漏洞以及Blind XXE总结「建议收藏」转载请注明出处:http://blog.csdn.net/u0117215010、前言XXE漏洞是针对使用XML交互的Web应用程序的攻击方法,在XEE漏洞的基础上,发展出了BlindXXE漏洞。目前来看,XML文件作为配置文件(Spring、Struts2等)、文档结构说明文件(PDF、RSS等)、图片格式文件(SVGheader)应用比较广泛,此外,网上有一些在线XML格式…

  • UART与USART区别

    UART与USART区别USART:通用同步和异步收发器UART:通用异步收发器当进行异步通信时,这两者是没有区别的。区别在于USART比UART多了同步通信功能。这个同步通信功能可以把USART当做SPI来用,比如用USART来驱动SPI设备。同步是指:发送方发出数据后,等接收方发回响应以后才发下一个数据包的通讯方式。 异步是指:发送方发出数据后,不等接收方发回响应,接着发送下

  • 为低端浏览器定义原型方法matchAll[通俗易懂]

    为低端浏览器定义原型方法matchAll[通俗易懂]String.prototype.matchAll=function(reg){letmatchArr=[];letmatch;while((match=reg.exec(this))!==null){matchArr.push(match);}returnmatchArr;};

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号