什么时候在 Ruby 中使用符号而不是字符串? [英] When to use symbols instead of strings in Ruby?

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

问题描述

如果我的脚本中至少有两个相同字符串的实例,我应该使用符号吗?

解决方案

TL;DR

一个简单的经验法则是每次需要内部标识符时都使用符号.对于 Ruby <2.2 仅在非动态生成的情况下使用符号,以避免内存泄漏.

完整答案

不将它们用于动态生成的标识符的唯一原因是内存问题.

这个问题很常见,因为许多编程语言没有符号,只有字符串,因此字符串也被用作代码中的标识符.您应该担心是什么符号,而不仅仅是什么时候应该使用符号.符号旨在作为标识符.如果您遵循这一理念,那么您很有可能会做对.

符号和字符串的实现有几个区别.符号最重要的一点是它们不可变.这意味着它们的价值永远不会改变.正因为如此,符号的实例化速度比字符串快,而且一些比较两个符号的操作也更快.

符号是不可变的这一事实允许 Ruby 每次引用该符号时都使用相同的对象,从而节省内存.因此,每次解释器读取 :my_key 时,它都可以从内存中取出它而不是再次实例化它.这比每次都初始化一个新字符串要便宜.

您可以使用命令Symbol.all_symbols 获取已实例化的所有符号的列表:

symbols_count = Symbol.all_symbols.count # all_symbols 是一个包含所有的数组# 实例化的符号.一个=:一个放置 a.object_id# 打印 167778一个=:两个放置 a.object_id# 打印 167858一个=:一个放置 a.object_id# 再次打印 167778 - 与第一次相同的 object_id!puts Symbol.all_symbols.count - symbols_count# 打印 2,我们创建的两个对象.

对于 2.2 之前的 Ruby 版本,一旦符号被实例化,该内存将不再可用.释放内存的唯一方法是重新启动应用程序.因此,符号使用不当也是导致内存泄漏的主要原因.产生内存泄漏的最简单方法是在用户输入数据上使用 to_sym 方法,因为这些数据总是会改变,新的内存部分将在软件实例中永远使用.Ruby 2.2 引入了符号垃圾收集器,它释放动态生成的符号,因此产生了内存泄漏通过动态创建符号,它不再是一个问题.

回答您的问题:

<块引用>

如果我的应用程序或脚本中至少有两个相同的字符串,我是否必须使用符号而不是字符串?

如果您要查找的是要在代码内部使用的标识符,则应该使用符号.如果你打印输出,你应该使用字符串,即使它出现不止一次,甚至在内存中分配两个不同的对象.

原因如下:

  1. 打印符号会比打印字符串慢,因为它们被转换为字符串.
  2. 拥有大量不同的符号会增加应用程序的整体内存使用量,因为它们永远不会被释放.而且您永远不会同时使用代码中的所有字符串.

@AlanDert 的用例

<块引用>

@AlanDert:如果我在 haml 代码中多次使用 %input{type::checkbox} 之类的东西,我应该使用什么作为复选框?

我:是的.

@AlanDert:但是要在html页面上打印一个符号,它应该转换为字符串,不是吗?那么使用它有什么意义呢?

输入的类型是什么?您要使用的输入类型的标识符或要向用户显示的内容?

它确实会在某个时候变成 HTML 代码,但是在您编写这行代码的那一刻,它的意思是成为一个标识符 - 它标识您需要什么样的输入字段.因此,它会在您的代码中反复使用,并且始终具有与标识符相同的字符字符串",并且不会产生内存泄漏.

也就是说,我们为什么不评估数据以查看字符串是否更快?

这是我为此创建的一个简单基准:

需要'基准'需要'haml'str = Benchmark.measure 做10_000 次做Haml::Engine.new('%input{type: "checkbox"}').render结尾最终总计sym = Benchmark.measure 做10_000 次做Haml::Engine.new('%input{type::checkbox}').render结尾最终总计puts "String:" + str.to_s放置符号:"+ sym.to_s

三个输出:

# 第一次字符串:5.14符号:5.07#第二字符串:5.29符号:5.050000000000001#第三字符串:4.7700000000000005符号:4.68

所以使用 smbols 实际上比使用字符串要快一些.这是为什么?这取决于 HAML 的实现方式.我需要对 HAML 代码进行一些修改才能看到,但是如果您继续在标识符的概念中使用符号,您的应用程序将更快更可靠.当问题出现时,对其进行基准测试并获得答案.

If there are at least two instances of the same string in my script, should I instead use a symbol?

解决方案

TL;DR

A simple rule of thumb is to use symbols every time you need internal identifiers. For Ruby < 2.2 only use symbols when they aren't generated dynamically, to avoid memory leaks.

Full answer

The only reason not to use them for identifiers that are generated dynamically is because of memory concerns.

This question is very common because many programming languages don't have symbols, only strings, and thus strings are also used as identifiers in your code. You should be worrying about what symbols are meant to be, not only when you should use symbols. Symbols are meant to be identifiers. If you follow this philosophy, chances are that you will do things right.

There are several differences between the implementation of symbols and strings. The most important thing about symbols is that they are immutable. This means that they will never have their value changed. Because of this, symbols are instantiated faster than strings and some operations like comparing two symbols is also faster.

The fact that a symbol is immutable allows Ruby to use the same object every time you reference the symbol, saving memory. So every time the interpreter reads :my_key it can take it from memory instead of instantiate it again. This is less expensive than initializing a new string every time.

You can get a list all symbols that are already instantiated with the command Symbol.all_symbols:

symbols_count = Symbol.all_symbols.count # all_symbols is an array with all 
                                         # instantiated symbols. 
a = :one
puts a.object_id
# prints 167778 

a = :two
puts a.object_id
# prints 167858

a = :one
puts a.object_id
# prints 167778 again - the same object_id from the first time!

puts Symbol.all_symbols.count - symbols_count
# prints 2, the two objects we created.

For Ruby versions before 2.2, once a symbol is instantiated, this memory will never be free again. The only way to free the memory is restarting the application. So symbols are also a major cause of memory leaks when used incorrectly. The simplest way to generate a memory leak is using the method to_sym on user input data, since this data will always change, a new portion of the memory will be used forever in the software instance. Ruby 2.2 introduced the symbol garbage collector, which frees symbols generated dynamically, so the memory leaks generated by creating symbols dynamically it is not a concern any longer.

Answering your question:

Is it true I have to use a symbol instead of a string if there is at least two the same strings in my application or script?

If what you are looking for is an identifier to be used internally at your code, you should be using symbols. If you are printing output, you should go with strings, even if it appears more than once, even allocating two different objects in memory.

Here's the reasoning:

  1. Printing the symbols will be slower than printing strings because they are cast to strings.
  2. Having lots of different symbols will increase the overall memory usage of your application since they are never deallocated. And you are never using all strings from your code at the same time.

Use case by @AlanDert

@AlanDert: if I use many times something like %input{type: :checkbox} in haml code, what should I use as checkbox?

Me: Yes.

@AlanDert: But to print out a symbol on html page, it should be converted to string, shouldn't it? what's the point of using it then?

What is the type of an input? An identifier of the type of input you want to use or something you want to show to the user?

It is true that it will become HTML code at some point, but at the moment you are writing that line of your code, it is mean to be an identifier - it identifies what kind of input field you need. Thus, it is used over and over again in your code, and have always the same "string" of characters as the identifier and won't generate a memory leak.

That said, why don't we evaluate the data to see if strings are faster?

This is a simple benchmark I created for this:

require 'benchmark'
require 'haml'

str = Benchmark.measure do
  10_000.times do
    Haml::Engine.new('%input{type: "checkbox"}').render
  end
end.total

sym = Benchmark.measure do
  10_000.times do
    Haml::Engine.new('%input{type: :checkbox}').render
  end
end.total

puts "String: " + str.to_s
puts "Symbol: " + sym.to_s

Three outputs:

# first time
String: 5.14
Symbol: 5.07
#second
String: 5.29
Symbol: 5.050000000000001
#third
String: 4.7700000000000005
Symbol: 4.68

So using smbols is actually a bit faster than using strings. Why is that? It depends on the way HAML is implemented. I would need to hack a bit on HAML code to see, but if you keep using symbols in the concept of an identifier, your application will be faster and reliable. When questions strike, benchmark it and get your answers.

这篇关于什么时候在 Ruby 中使用符号而不是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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