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

What is Java Virtual Machine(JVM)?

Tutorial using Google API Generation tools (GAPIC) to generate gRPC clients in golang

Useful Kubernetes Tools

Are your Software Training Programs leading nowhere? Simulations could be the missing link.

how to install vendor folder in laravel | Laravel autoload.php error

how to install vendor folder in laravel | Laravel autoload.php error

Quick Guide to responsively style with Bootstrap

Turn Your Spaghetti Code into Functions — Part 2

Create custom REST Resource for GET and POST method in Drupal 8

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

How to validate Value Object with “Valiktor”

KivaKit — Type Conversion

Decorator Design Pattern

Investigating Java Heap memory and Native memory leaks

JVM memory model