The Artima Developer Community
Sponsored Link

Scala Buzz
A More Efficient Option

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Jesper Nordenberg

Posts: 29
Nickname: megagurka
Registered: Dec, 2007

Jesper Nordenberg is a Scala hacker
A More Efficient Option Posted: Mar 11, 2013 5:06 PM
Reply to this message Reply

This post originated from an RSS feed registered with Scala Buzz by Jesper Nordenberg.
Original Post: A More Efficient Option
Feed Title: Jesper's Blog
Feed URL:
Feed Description: randomThoughts filter (_.category in (Scala :: programming :: Nil)) foreach
Latest Scala Buzz Posts
Latest Scala Buzz Posts by Jesper Nordenberg
Latest Posts From Jesper's Blog

Scala's Option type is a big improvement in type safety over Java's null checking and NullPointerException's. Unfortunately when wrapping a value in Some there is a quite big overhead: creation of one additional object containing a reference to the value. It would be more efficient if we could represent Some as the unboxed pointer value and encode None as the null value, but at the same time preserving the type safety as we get with the Option type (for example Kotlin uses this approach in it's builtin support for nullable types). Well, we can do exactly this with value classes introduced in Scala 2.10:

final case class Option[+T](value: T = null.asInstanceOf[T]) extends AnyVal with Product with Serializable {
def isEmpty: Boolean = value == null
The code is on GitHub if someone wants to try it out. It's pretty much a dropin replacement for the standard Scala Option type, except when pattern matching on None where one has to use None() instead.

Memory Usage Comparisons

Below is a comparison in memory usage between the Scala Option type and the unboxed AnyVal Option when allocating 1M objects each containing one optional value:

Scala Some: 33 MB
Scala None: 19 MB
AnyVal Some: 19 MB
AnyVal None: 19 MB
As one would expect, memory usage for Some is almost halved and for None the memory usage is unchanged.

Read: A More Efficient Option

Topic: Veripacks 0.3: importing packages (transitively, of course) Previous Topic   Next Topic Topic: xsbt-proguard-plugin - taking over, new release

Sponsored Links


Copyright © 1996-2018 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use