Lisp - Size of a Hash Table



In LISP, hashtable is a fundamental data structure. Its size grows as we add more key-values to it. Although during creation of a table using make-hash-table function, we can provide initial size, threshold to mark table too full to increase its size.

Syntax - make-hash-table function

(make-hash-table &key test size rehash-size rehash-threshold)

Where

  • test− a comparison function to compare keys of hashtable during search. Default is eql.

  • size− an implementation specific initial capacity of the hashtable for memory allocation.

  • rehash-size− to control the size of hash-table when its size is to expanded.

  • rehash-threshold− to mark hash-table size when it is marked as full.

Memory Consideration

Memory consumed by hashtable depends on several factors.

  • Key-Value Pairs− The number of key-value pairs stored in the table.

  • Size− Memory requirement of keys and Values.

  • Structure Overhead− Overhead memory required for hash table's internal data structure.

  • System implementation− System level implementation of LISP hash table.

Size Parameter

  • size parameter is a performance tuning parameter.

  • Using size in make-hash-table allows some control over initial size and resizing behavior.

In LISP, hash table is designed to handle varying amount of data.

Example - Getting Current Size of Hashtable

We can get the count of elements of Hashtable using hash-table-count function.

main.lisp

; create a hashtable
(defvar my-hash-table (make-hash-table)) 

; add key-value pairs to hash table
(setf (gethash '001 my-hash-table) 10)
(setf (gethash '002 my-hash-table) 20) 

; print the size of the hash table
(write (hash-table-count my-hash-table))

; add another entry
(setf (gethash '003 my-hash-table) 30) 
(terpri)
; print the size of the hash table
(write (hash-table-count my-hash-table))

Output

When you execute the code, it returns the following result −

2
3

Example - Getting Capacity of Hashtable

We can get the initial capacity of elements of Hashtable using hash-table-size function.

main.lisp

; create a hashtable
(defvar my-hash-table (make-hash-table)) 

; add key-value pairs to hash table
(setf (gethash '001 my-hash-table) 10)
(setf (gethash '002 my-hash-table) 20) 

; print the size of the hash table
(write (hash-table-size my-hash-table))

; add another entry
(setf (gethash '003 my-hash-table) 30) 
(terpri)
; print the size of the hash table
(write (hash-table-size my-hash-table))

Output

When you execute the code, it returns the following result −

2
3
  • hash-table-size function is used to get the hash table's capacity, as the memory allocated to a hash table. This function should be used to get the capacity of the hashtable.

  • hash-table-count function is used to get the number of elements present in the table. This function tells the actual number of elements present in the table.

Advertisements