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

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

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

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Headless模式_java策略模式

    Headless模式_java策略模式Headless模式是在缺少显示屏、键盘或者鼠标是的系统配置。在java.awt.toolkit和java.awt.graphicsenvironment类中有许多方法,除了对字体、图形和打印的操作外还可以调用显示器、键盘和鼠标的方法。但是有一些类中,比如Canvas和Panel,可以在headless模式下执行。Headless模式虽然不是我们愿意见到的,但事实上我们却常常需要在该模式下工作,尤…

    2022年10月27日
    0
  • java文件上传服务器路径,java文件上传服务器路径地址「建议收藏」

    java文件上传服务器路径,java文件上传服务器路径地址「建议收藏」java文件上传服务器路径地址内容精选换一换已获取自动化工具包,并上传到服务器完成解压,得到完整的软件文件夹tsdbtool。已下载依赖:GCC-7.3.0、CMake-3.5.2的源码包,放到tsdbtool文件夹下的postgresqlDep文件夹中,下载地址见表2。已获取PostgreSQL的源码包或者RPM包,并上传到自动化工具tsdbtool目录下。根据实际环境,完成安装将NFS文件系…

    2022年7月11日
    24
  • Spring源码阅读指南_redis编译安装

    Spring源码阅读指南_redis编译安装1.前言:经过多次拉取Spring源码编译失败经历,一下抓取配置编译过程各个软件版本可能有影响因此先做以记录(时间不同也会导致版本出入要注意)Idea:2020.1.1(参考文献博主2019.3.3版本也可)插件:maven(3.6.3)(未用到)Gradle(4.10.3)Kotlin(idea内装)JDK:原机安装1.8版本需要11版本(后续会说明JDK1.8问题)注:流程可能较长,源码拉取编译不易,耐心阅读2.流程2.1抓取Spring源码GITHUB网址:https://gi

    2022年8月12日
    7
  • stm32编程步骤_单片机STM32

    stm32编程步骤_单片机STM32近几年来,从云计算、大数据到机器学习、AI、物联网,各种新潮的技术概念一波~~接一波。于是就产生了一些好奇心旺盛,抱着去凑一凑热闹的心态,实际上却是也想分一杯羹儿的程序员!但问题是,在他们的技术栈里,一切…

    2022年9月6日
    5
  • 网站模板 收集[通俗易懂]

    网站模板 收集[通俗易懂]http://www.wzjs.info/bz.asp?classid=130http://www.wzjs.info/网站超市https://www.kuicms.com/魅网https://templets.kui.net/k0001/https://templets.kui.net/k0205/魅网内页(可直接扣)https://www.sitestar.cn/website/combination_templates.aspx?type=all建站之星(可扣)h…

    2022年7月24日
    5
  • 树莓派 Raspberry Pi 连接 WiFi

    树莓派 Raspberry Pi 连接 WiFi说明开启Wifi的不同情况说明:第一种情况:有显示器和鼠标键盘1.1:桌面操作开启WiFi,包含桌面图形的系统(RaspbianStretchwithdesktop)1.2:通过树莓派配置,适用带桌面或仅命令行的系统。1.3:直接修改配置文件,适用带桌面或仅命令行的系统。第二种情况:无显示器和鼠标键盘2.1:使用另一台可用电脑编辑SD卡(但我尝试不成功,ORZ,望…

    2022年5月18日
    40

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

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