Scala Symbol explanation and usage

1. Introduction

Symbols can be used as a quick way to compare strings. If the values ​​of the strings are the same, the returned symbol variable has the same reference address. Symbol maintains a string pool internally.

object SymbolDemo {
    
    
  def main(args: Array[String]): Unit = {
    
    
    val s = 'nihao
    val n = 'nihao
    // return true
    println(s == n)
    // return true
    println(s == 'nihao)
  }
}

Second, the following describes the two characteristics of the Symbol type.

  1. Saving memory
    In Scala, Symbol type objects are interned, and any symbols with the same name point to the same Symbol object, avoiding the memory overhead caused by redundancy. For the String type, only the string determined at compile time is interned. The Scala test code is as follows:
  2. Quick comparison
    Because the Symbol type object is interned, any symbols with the same name point to the same Symbol object, and symbols with different names must point to different Symbol objects, so the operator == fast can be used between symbol objects Equality comparison can be done in a constant time, and the equals method of a string needs to compare two strings character by character. The execution time depends on the length of the two strings, which is very slow. (In fact, the String.equals method will first compare whether the references are the same, but the references to string objects generated at runtime are generally different)

Three, Symbol type applications

Symbol type is generally used for quick comparison, such as Map type: Map<Symbol, Data>, according to a Symbol object, you can quickly query the corresponding Data, while the query efficiency of Map<String, Data> is much lower.

Guess you like

Origin blog.csdn.net/weixin_44455388/article/details/107918728