Symbols and Internalising Strings

Before we talk about Symbol….

Some code in Python

String with same contents share same id?

  • It means, when we tried to define y with the same content as that of x, the application looked up the heap/memory and identified that y could reuse the contents of x.
  • If y needs to re-use x, obvious that they should have the same object_id. id (x) == id (y)
  • No extra copy of y is created, and we saved some space.

In Java/Scala?

  • In computer science, the behaviour is termed as string interning. That is, internalising the strings will ensure that all strings with same contents share the same memory.
  • One source of drawbacks is that string interning may be problematic when mixed with multithreading, but this discussion is out of scope.
  • In the above examples with python/ruby, the string x is internalized automatically, so is for Java/Scala. (However, you will find differences in behavior across these languages soon)
  • In java, String.intern() internalise the strings forcefully, but you don’t do this generally.
  • The intern() method returns a canonical representation of the string object.

Automatic String interning: naive testing in Scala (Skip through if you don’t care)

Is interning a property of Strings?

Is this a consistent behaviour for Strings?

No default string intern in Ruby?

How to intern strings in Ruby?

Symbol

Symbol in Ruby

Some performance comparison:

Usage of symbols:

Are symbols always better than strings?

Symbol in Python

Symbols in Clojure

Conclusion

--

--

--

A software engineer and a functional programming enthusiast at Simple-machines, Sydney, and a hardcore hiking fan. https://twitter.com/afsalt2

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

A Short Introduction to PySpark Window Functions

Angular 101 — A Technical Understanding OnWhere It Fits in Application Development

Ruby on Rails API — Flatiron School Project

Flutter 起步 Day 3 — 側邊選單(Drawer)

Preparing for $L3P Staking

re:Invent 2020, Week 1 Talk Highlights

Fundamentals of User Stories

How to use Golden Master testing for your iOS apps

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Afsal Thaj

Afsal Thaj

A software engineer and a functional programming enthusiast at Simple-machines, Sydney, and a hardcore hiking fan. https://twitter.com/afsalt2

More from Medium

It’s all about engineering a load balancer: Types, Configuration & Algorithms

JAVA 16 And 17: Evolutions and new features — Part 2

A* Algorithm in droplets — Pt.1

Shutdown Hooks for JVM Applications