Scala Symbol explanation

Symbol

This class provides a simple way to get unique objects for equal strings. Since symbols are interned, they can be compared using reference equality.

symbols can be used as a quick way to compare a string, if the string is the same as the value that is returned with the same reference symbol variable address. Internal Symbol maintains a string pool.

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

Compare to Java

In Java String instance created in two ways:
one, to direct a variable assignment;
2, creates a String object with the new key; (hereinafter referred to as: mode 1 and mode 2)

Mode 1

We all know that "Mode 1" each time to create a new variable (so for the inner loop stitching string does not recommend using the "+" operator, because every time to open up a new memory). But in fact, Java is optimized for the operation, within the String class maintains a string pool, each time by "Mode 1" Create a String instance, first check the string pool have no same string, if the string pool in the string does not exist, the string into the string pool (open new memory here), while the reference to the string assigned to the variable address; if the string pool there is the string, the original direct there are references to the address assigned to a new variable.

When you create a "str1", the string pool is no "Hello Str", this time the "Hello Str" into the string pool, and a memory address assigned to the "str1". When you create a "str2", the string pool already exist "Hello Str", directly to the original memory address assignment to "str2", it returns "str1 == str2" true.

Mode 2

Each time a new object is created, when calling intern () procedure with logic "mode 1". When there is "Hello Str" string pool return memory address directly, or they will "Hello Str" into the string pool, and returns the memory address.

public class Demo {

  public static void main(String[] args) { String str1 = "Hello Str"; String str2 = "Hello Str"; String str3 = new String("Hello Str"); // return true System.out.println(str1 == str2); // return false System.out.println(str1 == str3); // return true System.out.println(str1 == str3.intern()); } } 

Refer from: 

https://yq.aliyun.com/articles/668857
https://www.scala-lang.org/api/2.12.1/scala/Symbol.html
https://stackoverflow.com/questions/3554362/purpose-of-scalas-symbol

Guess you like

Origin www.cnblogs.com/barrywxx/p/11441348.html