简体   繁体   English

JS字符串/数字和垃圾收集

[英]JS Strings/Numbers and Garbage Collection

tl;dr TL;博士

Does the following line of code create an object (like a JavaScript String object or a JavaScript Number object) to combine the string primitive and the number? 以下代码行是否创建了一个对象(如JavaScript String对象或JavaScript Number对象)来组合字符串原语和数字?

var scouterSays = "powerlvl" + 9001;

Full Question 完整问题

I'm writing a game engine in JavaScript and am trying to be very careful with garbage collection. 我正在用JavaScript编写游戏引擎,并且我正在努力对垃圾收集非常小心。 I've read through http://www.scirra.com/blog/76/how-to-write-low-garbage-real-time-javascript and http://buildnewgames.com/garbage-collector-friendly-code/ which have been very helpful. 我已经阅读了http://www.scirra.com/blog/76/how-to-write-low-garbage-real-time-javascripthttp://buildnewgames.com/garbage-collector-friendly-code /这是非常有帮助的。 I've implemented object pooling and have avoided array manipulation in favor of linked lists whenever possible. 我已经实现了对象池并且尽可能避免了数组操作以支持链表。

Now if I understand it correctly, if I call a string method on a primitive string, a string object will be created and replaces my primitive string. 现在,如果我理解正确,如果我在原始字符串上调用字符串方法,将创建一个字符串对象并替换我的原始字符串。 Examples are length, substring, indexOf, and so on. 示例是length,substring,indexOf等。 Since I use strings to identify object types with object pooling, I am concerned that I am creating garbage each time I pull an object from the pool. 由于我使用字符串来识别带有对象池的对象类型,因此我担心每次从池中提取对象时都会创建垃圾。

In short, will the following cause an object (like a JavaScript String object or a JavaScript Number object) to be created? 简而言之,以下是否会导致创建对象(如JavaScript String对象或JavaScript Number对象)?

var byteSize = 4;
var objectType = "msg" + byteSize; //does this create a JS String/Number object?
var message = gameengine.pool.acquire(objectType);

Also, a related question, will use of bitwise operations (like ~~() or << or >>) cause a JavaScript object to be created as well? 另外,一个相关的问题,将使用按位运算(如~~()或<<或>>)也会导致创建一个JavaScript对象?

I have zero trust to JavaScript GC and this is my base reason to stay away from this language. 我对JavaScript GC没有信任,这是我远离这种语言的基本理由。 Anyway, my attempt to reply is: 无论如何,我的回复尝试是:

var x = 1;
alert(typeof x); //number

var n = new Number(1);
alert(typeof n); //object

var scouterSays = "powerlvl" + 9001;
alert(typeof scouterSays); //string

var txt = new String("string");
alert(typeof txt); //object

var test1 = new Boolean(true);
var test2 = String(test1); //convert object to string
alert(typeof test2); //string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM