title: References sidebar_position: 50 id: references license: | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
By default Fory treats every value as a separate copy — if the same object appears in two fields it gets serialized twice, and after deserialization you get two independent copies. Enable reference tracking when:
Leave reference tracking off for plain tree-shaped data; it adds a small overhead.
Fory Instanceconst fory = new Fory({ ref: true });
For each field whose value may be shared or circular, call .setTrackingRef(true) on the field's schema:
const nodeType = Type.struct("example.node", { value: Type.string(), next: Type.struct("example.node").setNullable(true).setTrackingRef(true), });
You need both the global flag and the field-level flag. Missing either one results in values being copied rather than referenced.
import Fory, { Type } from "@apache-fory/core"; const nodeType = Type.struct("example.node", { name: Type.string(), selfRef: Type.struct("example.node").setNullable(true).setTrackingRef(true), }); const fory = new Fory({ ref: true }); const { serialize, deserialize } = fory.register(nodeType); const node: any = { name: "root", selfRef: null }; node.selfRef = node; const copy = deserialize(serialize(node)); console.log(copy.selfRef === copy); // true
const innerType = Type.struct(501, { value: Type.string(), }); const outerType = Type.struct(502, { left: Type.struct(501).setNullable(true).setTrackingRef(true), right: Type.struct(501).setNullable(true).setTrackingRef(true), }); const fory = new Fory({ ref: true }); const { serialize, deserialize } = fory.register(outerType); const shared = { value: "same-object" }; const copy = deserialize(serialize({ left: shared, right: shared })); console.log(copy.left === copy.right); // true
Enable reference tracking when:
Leave it disabled when:
Reference tracking is part of the Fory binary protocol and works across runtimes. Both sides must enable reference tracking and mark the same fields as reference-tracked for the behavior to be consistent.