Skip to main content

Symbol

Overview

A Symbol is a primitive data type that represents a unique, immutable identifier. Unlike strings, symbols are primarily used for identity rather than textual content. Two symbols with the same description are still considered different if they are created separately.

Symbols are commonly used in language runtimes, compilers, and metaprogramming systems.


What Is a Symbol?

A symbol consists of:

  • An optional name or description
  • A guaranteed unique identity

Equality is based on identity, not on textual value.


How It Works

When a symbol is created:

  • The runtime generates a unique internal identifier
  • That identity never changes
  • Comparisons check identity, not content

Some systems provide interned symbols, where identical names map to the same symbol.


Symbol vs String

AspectSymbolString
MutabilityImmutableUsually mutable
ComparisonBy identityBy value
Use caseIdentifiers, keysText data
PerformanceFast lookupsSlower comparisons

Common Operations

  • Creation
  • Identity comparison
  • Use as keys
  • Metadata tagging

Example

Pseudocode

sym1 = Symbol("id")
sym2 = Symbol("id")

sym1 == sym2 // false

Even though they look the same, they are distinct.

Real-world Analogy

A symbol is like a barcode. Two products may have the same name, but each barcode uniquely identifies an item.


Time and Space Complexity

  • Space: O(1)
  • Comparison: O(1)

Use Cases

  • Language interpreters
  • Abstract syntax trees
  • Configuration keys
  • Avoiding name collisions
  • Metaprogramming

Advantages

  • Guaranteed uniqueness
  • Fast equality checks
  • Safe as map keys

Limitations

  • Not meant for user-facing text
  • Can increase memory usage if overused