什么时候不应该在 Ruby 中使用 to_sym? [英] When not to use to_sym in Ruby?

查看:42
本文介绍了什么时候不应该在 Ruby 中使用 to_sym?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自分析提供商的大型数据集.

I have a large dataset from an analytics provider.

它以 JSON 格式到达,我将其解析为一个哈希值,但由于集合的大小,我的内存使用量激增.几乎所有的东西都以字符串开头(一些值是数字),当然,虽然键被重复了很多次,但许多值也被重复了.

It arrives in JSON and I parse it into a hash, but due to the size of the set I'm ballooning to over a gig in memory usage. Almost everything starts as strings (a few values are numerical), and while of course the keys are duplicated many times, many of the values are repeated as well.

所以我在想,为什么不象征所有(非数字)值呢?

So I was thinking, why not symbolize all the (non-numerical) values, as well?

我发现了一些潜在问题的讨论,但我认为对 Ruby 进行全面描述会很好,因为这些问题似乎取决于实习过程的实现(当你符号化一个字符串时会发生什么).

I've found some discusion of potential problems, but I figure it would be nice to have a comprehensive description for Ruby, since the problems seem dependent on the implementation of the interning process (what happens when you symbolize a string).

我发现这是在谈论 Java:使用 java.lang.String 是个好习惯吗?实习生()?

I found this talking about Java: Is it good practice to use java.lang.String.intern()?

  • 实习过程可能很昂贵
  • interned 字符串永远不会被取消分配,从而导致内存泄漏

(除了最后一点有争议.)

(Except there's some contention on that last point.)

那么,谁能详细解释一下什么时候不要在 Ruby 中实习字符串?

So, can anyone give a detailed explanation of when not to intern strings in Ruby?

推荐答案

  • 当所讨论的事物列表是一个开放集(即动态的,没有固定库存)时,您不应将它们转换为符号.创建的每个符号都不会被垃圾回收,并且会导致内存泄漏.
  • 当所讨论的事物列表是封闭集(即静态的,有固定库存)时,您最好将它们转换为符号.每个符号只会被创建一次,并将被重复使用.这将节省内存.
  • 这篇关于什么时候不应该在 Ruby 中使用 to_sym?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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