Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying the size of a HashMap in Scala

Tags:

hashmap

scala

I'm using Scala's mutable HashMap to incrementally add up to millions of key-value pairs. The resizing of these HashMaps is now the slowest part of my program. How can I tell Scala to create a very large HashMap from the start so that it (almost) never needs to be resized?

I would appreciate also any ideas that propose another Scala/Java collection that would suit my needs. Adding a new key-value pair and retrieving a value given a key should both be doable in approximately constant time.

like image 244
Bruno Avatar asked Mar 26 '14 07:03

Bruno


2 Answers

One of possible way:

import scala.collection.mutable.{HashTable, DefaultEntry}

trait BigHashTable[A, B] extends HashTable[A, DefaultEntry[A, B]] {
  override def initialSize: Int = 1024 // 16 - by default
}

val x = new HashMap[Int, String] with BigHashTable[Int, String]

another one:

class MyHashMap[A, B](initSize : Int) extends HashMap[A, B] {
  override def initialSize: Int = initSize // 16 - by default
}

val x = new MyHashMap[Int, String](1024)
like image 99
Yuriy Avatar answered Oct 18 '22 21:10

Yuriy


scala.collection.mutable.OpenHashMap supports initialSize

like image 3
jifeng.yin Avatar answered Oct 18 '22 20:10

jifeng.yin