# Wolfram Function Repository

Instant-use add-on functions for the Wolfram Language

Function Repository Resource:

Determine if two Wolfram Language expressions come from the same instance

Contributed by:
Jason Biggs

ResourceFunction["SameInstanceQ"][ returns True if | |

ResourceFunction["SameInstanceQ"][ returns True if all the |

Two expressions share the same instance if they represent pointers to the same data—in other words, if they occupy the same location in memory.

Two expressions that are identical are considered SameQ:

In[1]:= |

Out[3]= |

However, they are different instances of the same data:

In[4]:= |

Out[4]= |

By contrast, the value for *c* in the below is literally the same value for *a*, since both reference the same memory location:

In[5]:= |

Out[6]= |

SameInstanceQ can accept any number of arguments:

In[7]:= |

Out[7]= |

In[8]:= |

Out[8]= |

SameInstanceQ always returns True for a single argument:

In[9]:= |

Out[9]= |

In[10]:= |

Out[10]= |

Compare to SameQ:

In[11]:= |

Out[11]= |

In[12]:= |

Out[12]= |

SameInstanceQ[] is defined to be True:

In[13]:= |

Out[13]= |

This matches the behavior of SameQ:

In[14]:= |

Out[14]= |

Memory is typically allocated for each new expression that is created, even if it shares the same value as an existing expression:

In[15]:= |

Out[14]= |

In this case, *a* and *b* have identical values:

In[16]:= |

Out[16]= |

However, their values are stored separately in memory, since each expression was created separately:

In[17]:= |

Out[17]= |

Reusing expressions that are already created can save memory:

In[18]:= |

Out[19]= |

The value for *a* is literally the same value for *b*, since both reference the same memory location:

In[20]:= |

Out[20]= |

Many simple expressions are already preallocated in the kernel:

In[21]:= |

Out[21]= |

In[22]:= |

Out[22]= |

These are not necessarily atomic values:

In[23]:= |

Out[23]= |

Atomic expressions that are SameQ are not necessarily SameInstanceQ:

In[24]:= |

Out[24]= |

In[25]:= |

Out[25]= |

In[26]:= |

Out[26]= |

Having all of the corresponding parts of expressions be SameInstanceQ does not imply the parent expressions are SameInstanceQ:

In[27]:= |

In[28]:= |

Out[28]= |

In[29]:= |

Out[29]= |

In[30]:= |

Out[30]= |

In[31]:= |

Out[31]= |

Small integers are already created in memory, so they are always the same instance:

In[32]:= |

Out[32]= |

Larger integers are created as needed:

In[33]:= |

Out[33]= |

Find the range of small integers that are preallocated in memory:

In[34]:= |

Out[34]= |

Test modifications on expressions to see which lead to new instances:

In[35]:= |

In[36]:= |

Out[36]= |

In[37]:= |

Out[37]= |

In[38]:= |

Out[38]= |

In[39]:= |

Out[39]= |

In[40]:= |

Out[40]= |

- 1.0.0 – 11 May 2020

This work is licensed under a Creative Commons Attribution 4.0 International License