如何在脚本语言中为变量完成内存分配? [英] How is the memory allocation done for variables in scripting languages?

查看:150
本文介绍了如何在脚本语言中为变量完成内存分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在javascript中

For example, in javascript

我可以说

var x = 5;

稍后我可以做

x = 'a';

然后

x = "hello";

那么,如何为变量分配内存?实际上,所有变量都有一个共同类型'var',变量值可以在运行时改变,如上所示。为这些变量分配和管理内存不是一项艰巨的任务吗?究竟是怎么做的?

So, how is memory allocated for the variables? As it is, all variables have a common type 'var' and values of variables can change at run-time as seen above. Isn't it a difficult task to allocate and manage memory for these variables? Exactly, how is it done?

推荐答案

Python使用一种名为引用计数,它基本上将计数器放入值中。每次创建对值的引用时,计数器都会递增。当对值的引用丢失时(例如,当您为x分配新值时),该值将减少。当计数器达到零时,这意味着不存在对该值的引用,并且可以将其解除分配。这是一个简化的解释,但这至少是基础。

Python uses a technique called reference counting, which basically puts a counter in the value. Each time a reference to a value is created, the counter is incremented. When a reference to the value is lost (for instance when you assign a new value to 'x'), the value is decremented. When the counter reaches zero, that means that no reference to the value exists, and it can be deallocated. This is a simplified explanation, but that's at least the basics.

这篇关于如何在脚本语言中为变量完成内存分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆