开发者

Javascript variable reuse?

开发者 https://www.devze.com 2023-02-03 07:06 出处:网络
Is it OK to reuse variables for different data types in terms of performan开发者_如何转开发ce and memory usage ?

Is it OK to reuse variables for different data types in terms of performan开发者_如何转开发ce and memory usage ?

What happens to old data, is it garbage collected immediately after type casting ?


It's OK to reuse variables, although unless you're doing some crazy things (say so in the question) with the amount of variables you're using, you probably should not reuse them too liberally in this way. It's considered good coding practice in general to have a variable declared to point to a specific thing, and use a different variable when you want to refer to something else.

"Variables" in Javascript are just references. They're not inherently expensive-- they don't take up more space than their text in the code and a few bytes in memory pointing to somewhere else. If you reuse a variable name by setting the reference to something else (or null/undefined), then the GC will know that that original reference is detached and know that it can be collected.

The GC in whatever browser or environment you're using will choose when to actually run the collector based on lots of factors.


Full disclosure: I have no knowledge of the internals of any particular JavaScript engines. I'm going from general principles of VMs and interpreters.

Usually, variable names just refer to other memory locations. So, whether you remove an old variable (which happens when it goes out of scope) and introduce a new one, or replace the current contents with a new object, doesn't matter much in terms of memory allocation.

Garbage collection might be different in each implementation. Immediate garbage collection is difficult; the only way I can think of doing it involves reference counters, and it's tough to make that work even for cyclic data structures. So, most garbage collectors in the wild do non-immediate collection cycles where, each time, a whole bunch of data gets removed. The cycles might, for example, be run automatically when memory use goes above a certain threshold within the engine (but it'll usually be more refined than that).


JavaScript is a loosely-typed language, and can store any datatype in any variable (even reused ones).

If you are combining types, though, you should check them periodically using the typeof keyword to ensure they are the type you think they are (for instance, trying to perform a mathematical operation on a string will concatenate or break, depending on the situation).

Furthermore, JavaScript variables stick around as long as they are within scope. Once a scope is left, the variables within it are destroyed (eventually - it's automatic and transparent). As far as garbage collection on reassigned variables, the old value is destroyed as soon as the new value is assigned.

0

精彩评论

暂无评论...
验证码 换一张
取 消