D7net
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
proc
/
self
/
root
/
opt
/
alt
/
ruby34
/
share
/
ri
/
system
/
ObjectSpace
/
WeakKeyMap
/
Filename :
cdesc-WeakKeyMap.ri
back
Copy
U:RDoc::NormalClass[iI"WeakKeyMap:ETI"ObjectSpace::WeakKeyMap;TI"Object;To:RDoc::Markup::Document:@parts[o;;[o:RDoc::Markup::Paragraph;[I"NAn ObjectSpace::WeakKeyMap is a key-value map that holds weak references ;TI"Tto its keys, so they can be garbage collected when there is no more references.;To:RDoc::Markup::BlankLine o; ;[I"!Unlike ObjectSpace::WeakMap:;T@o:RDoc::Markup::List: @type:BULLET:@items[o:RDoc::Markup::ListItem:@label0;[o; ;[I"Oreferences to values are _strong_, so they aren't garbage collected while ;TI"they are in the map;;To;;0;[o; ;[I"Ekeys are compared by value (using Object#eql?), not by identity;;To;;0;[o; ;[I":only garbage-collectable objects can be used as keys.;T@o:RDoc::Markup::Verbatim;[I"'map = ObjectSpace::WeakKeyMap.new ;TI"!val = Time.new(2023, 12, 7) ;TI"key = "name" ;TI"map[key] = val ;TI" ;TI"F# Value is fetched by equality: the instance of string "name" is ;TI"2# different here, but it is equal to the key ;TI"/map["name"] #=> 2023-12-07 00:00:00 +0200 ;TI" ;TI"val = nil ;TI"GC.start ;TI"A# There are no more references to `val`, yet the pair isn't ;TI"# garbage-collected. ;TI"/map["name"] #=> 2023-12-07 00:00:00 +0200 ;TI" ;TI"key = nil ;TI"GC.start ;TI"@# There are no more references to `key`, key and value are ;TI"# garbage-collected. ;TI"map["name"] #=> nil ;T:@format0o; ;[I"R(Note that GC.start is used here only for demonstrational purposes and might ;TI".not always lead to demonstrated results.);T@o; ;[I"VThe collection is especially useful for implementing caches of lightweight value ;TI"Tobjects, so that only one copy of each value representation would be stored in ;TI"Hmemory, but the copies that aren't used would be garbage-collected.;T@o;;[I"%CACHE = ObjectSpace::WeakKeyMap ;TI" ;TI"def make_value(**) ;TI"" val = ValueObject.new(**) ;TI"+ if (existing = @cache.getkey(val)) ;TI"@ # if the object with this value exists, we return it ;TI" existing ;TI" else ;TI", # otherwise, put it in the cache ;TI" @cache[val] = true ;TI" val ;TI" end ;TI" end ;T;0o; ;[I"[This will result in +make_value+ returning the same object for same set of attributes ;TI"`always, but the values that aren't needed anymore wouldn't be sitting in the cache forever.;T: @fileI"weakmap.c;T:0@omit_headings_from_table_of_contents_below0;0;0[ [ [ [[I" class;T[[:public[ [:protected[ [:private[ [I" instance;T[[;[[I"[];TI"weakmap.c;T[I"[]=;T@o[I" clear;T@o[I"delete;T@o[I"getkey;T@o[I"inspect;T@o[I" key?;T@o[;[ [;[ [ [U:RDoc::Context::Section[i 0o;;[ ;0;0[I"ext/objspace/objspace.c;TI"ObjectSpace;TcRDoc::NormalModule