Skip to main content
Background Image
  1. Posts/

Set vs Map Collection Comparison

Cayden
Author
Cayden
Independent developer sharing daily experiences, challenges and growth in the journey of building products
Table of Contents
Feature ComparisonSetWeakSetMapWeakMap
Initializationnew Set([1,2,3,4])new WeakSet([1,2,3,4])new Map([["name", "Bright"], ["sex", "男"]])new WeakMap([["name", "Bright"], [" sex", "男"]])
DefinitionAn ordered list containing multiple non-duplicate valuesA special Set collection that only supports storing weak references to objectsAn ordered collection of multiple key-value pairsA special Map collection that only supports object-type keys
IterableYesNoYesNo
Reference FeatureMember objects strong referenceMember objects weak referenceMember objects strong referenceMember objects weak reference
Properties & Methodsadd() has() delete() clear() forEach() keys() values() sizeadd() has() delete()set() get() has() delete() clear() forEach() keys() values() sizeset () get() has() delete()
Usage RecommendationDue to the limitations of object property existence detection, this collection is more suitable for detecting whether a given value exists in the collection. Based on its non-duplicate value feature, it can be used for array deduplicationCan only store object types and facilitates tracking of referenced objectsUsed for handling key-value pair data, storing data that needs frequent accessUsed for handling key-value pair data, keys can only store object types, and facilitates tracking of referenced objects. The main use is to save DOM elements of web pages

Iterable
#

Whether iterable is used to indicate whether the collection supports traversing member properties, including the use of methods such as forEach(), keys(), values(), for…of, etc.

Object Limitations
#

Using if in objects to determine whether a value exists is not rigorous enough. When the property itself doesn’t exist and exists with a value of false, the judgment results are the same, which brings problems. There’s another method to determine whether a property exists in an object using ‘in’, but this method will traverse up the inherited prototype properties, also bringing some unknown problems, unless the object inherits from null.

Strong Reference
#

As long as the reference exists, the garbage collection mechanism will not release the memory space of the referenced object.

Weak Reference
#

When the referenced object is set to null, the collection doesn’t save the reference, triggering the garbage collection mechanism.