Skip to content

Reuse objects when inserting identical keys/values in PathCopyingPersistentTreeMap - #66

Open
PhilippWendler wants to merge 3 commits into
mainfrom
pathcopyingpersistenttreemap-reuse-on-insertion
Open

PhilippWendler wants to merge 3 commits into
mainfrom
pathcopyingpersistenttreemap-reuse-on-insertion

Conversation

@PhilippWendler

Copy link
Copy Markdown
Member

This PR affects cases where objects are inserted into a PathCopyingPersistentTreeMap and the value is identical (as defined by ==) as the old value for the same key. Now we reuse the old key object (even if it is not the same instance as the newly given key object) and then can reuse also the same Node and map objects, saving a little bit of memory for the cost of a single == comparison on re-inserting with the same key.

Map keys need to have well-defined equality (here actually compareTo() because it is a sorted map), so code that would rely on getting a specific instance of a key and breaks with other instances of an equal key is broken anyway and relies on assumptions that were never guaranteed.

Note that we do not pose any assumptions on value equality, as it is legal to put arbitrary objects as values into maps, even if they have broken/non-standard equals, and expect to get the same instance back as put last. This is for example necessary for safely putting mutable data structures like lists as values into a map.

The new behavior is the same as for JDK's HashMap and TreeMap, and there are tests for confirming this.

@lembergerth @baierd Might one of you want to review this?

In this case we can reuse the same object instances as the input.

This has no visible behavior change except that the map object sometimes
remains the same instance after putAndCopy().
But this is not what anyone would rely on,
as it is common for persistent data structures to do things like this.
For example, removeAndCopy() also returns the same map object
if there are no changes.
This affects cases where a new object that compares equal
to an existing key object is used for insertion.
Previously PathCopyingPersistentTreeMap would use the new key object,
now we use the old key object.

There are no strict rules on what to use,
but this is what HashMap and TreeMap do (as seen in some new tests),
and so it is not a bad idea to be consistent.
Also it allows us to reuse the same object a little bit more often
(if identical value with new key object is inserted).
@lembergerth

Copy link
Copy Markdown
Contributor

I think @baierd is quite busy at the moment; @baierd if that's true and you don't insist on reviewing this PR, I can do it (but I don't want to do double work)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

2 participants