本文介绍了Ruby符号不是垃圾收集!?那么,使用String不是更好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在循环中创建10,000个字符串,则必须进行大量垃圾回收,这会占用大量资源。



如果您执行相同的操作使用符号,您可以创建。



哪个更糟?

解决方案

Seeing因为符号几乎总是通过文字创建的,所以这里的内存爆炸的可能性不大。他们的行为非常需要他们的用法:每次引用一个符号时,都是一样的。

同样,Ruby中的字符串也必须是唯一的。这是由于它们被使用的方式 - 文本处理等。

根据它们的语义决定使用哪一个,不要过早地优化。


If you create 10,000 strings in a loop, a lot of garbage collection has to take place which uses up a lot of resources.

If you do the same thing with symbols, you create objects which cannot be garbage collected.

Which is worse?

解决方案

Seeing as symbols are almost always created via literals, there isn't much potential for a memory explosion here. Their behavior is pretty much required by their usage: every time you refer to a symbol, it's the same one.

Similarly, strings need to be unique in Ruby. This is due to the way they're used - text processing etc.

Decide which one to use depending on their semantics, don't optimize prematurely.

这篇关于Ruby符号不是垃圾收集!?那么,使用String不是更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 04:36