From 30ce70714ff49258aa5bcf9d83290cc2c1d44747 Mon Sep 17 00:00:00 2001 From: Cihad GUNDOGDU Date: Tue, 24 Nov 2026 16:03:17 +0300 Subject: [PATCH 1/2] Test that writing a DXF scales linearly with blocks and objects Four times the block records and dictionary objects take 14.2 times as long to write (316 ms -> 4.48 s in a debug build): every block record that names no extension dictionary has its owner looked up in every object of the document. Red until the lookup is gathered once per write. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GBAJR1pu3dhJEV6kKtxAfp --- tests/dxf_write_scaling.rs | 79 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 tests/dxf_write_scaling.rs diff --git a/tests/dxf_write_scaling.rs b/tests/dxf_write_scaling.rs new file mode 100644 index 00000000..43c276fe --- /dev/null +++ b/tests/dxf_write_scaling.rs @@ -0,0 +1,79 @@ +//! Writing a DXF takes time in proportion to the drawing: four times the blocks and objects take well under sixteen +//! times as long. A table record that names no extension dictionary has its owner looked up in every object of the +//! document (`CadDocument::extension_dictionary_handle`), and the writer asks for every block record, so a drawing of +//! many blocks (every dimension has one) and many objects is quadratic to write. + +use std::time::{Duration, Instant}; + +use acadrust::entities::{EntityType, Line}; +use acadrust::objects::{Dictionary, ObjectType}; +use acadrust::tables::BlockRecord; +use acadrust::types::{DxfVersion, Vector3}; +use acadrust::{CadDocument, DxfWriter}; + +/// A drawing of `n` blocks of one line each, and `n` lines in model space, each with an extension dictionary. +fn drawing(n: usize) -> CadDocument { + let mut doc = CadDocument::with_version(DxfVersion::AC1032); + for b in 0..n { + let mut record = BlockRecord::new(format!("B{b}")); + record.handle = doc.allocate_handle(); + record.block_entity_handle = doc.allocate_handle(); + record.block_end_handle = doc.allocate_handle(); + let owner = record.handle; + doc.block_records.add(record).unwrap(); + let mut line = Line::from_points(Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 0.0)); + line.common.owner_handle = owner; + doc.add_entity(EntityType::Line(line)).unwrap(); + } + for i in 0..n { + let x = i as f64; + let line = doc + .add_entity(EntityType::Line(Line::from_points( + Vector3::new(x, 0.0, 0.0), + Vector3::new(x, 1.0, 0.0), + ))) + .unwrap(); + let mut dictionary = Dictionary::new(); + dictionary.handle = doc.allocate_handle(); + dictionary.owner = line; + dictionary.hard_owner = true; + let handle = dictionary.handle; + doc.objects.insert(handle, ObjectType::Dictionary(dictionary)); + doc.get_entity_mut(line).unwrap().common_mut().xdictionary_handle = Some(handle); + } + doc +} + +fn fastest_write(doc: &CadDocument) -> (Duration, Vec) { + let mut best: Option<(Duration, Vec)> = None; + for _ in 0..3 { + let t = Instant::now(); + let bytes = DxfWriter::new(doc).write_to_vec().unwrap(); + let e = t.elapsed(); + if best.as_ref().is_none_or(|(b, _)| e < *b) { + best = Some((e, bytes)); + } + } + best.unwrap() +} + +#[test] +fn writing_many_blocks_and_objects_to_dxf_scales_linearly() { + const N: usize = 3_000; + let (small, large) = (drawing(N), drawing(N * 4)); + let (a, _) = fastest_write(&small); + let (b, bytes) = fastest_write(&large); + let text = String::from_utf8_lossy(&bytes); + assert_eq!( + text.matches("{ACAD_XDICTIONARY").count(), + N * 4, + "every model space line keeps its extension dictionary" + ); + // Linear is 4x, quadratic 16x; below a few milliseconds the ratio is noise. + let ratio = b.as_secs_f64() / a.as_secs_f64().max(0.005); + eprintln!("{N} blocks {a:?}, {} blocks {b:?}, ratio {ratio:.1}", N * 4); + assert!( + ratio < 9.0, + "4x the blocks and objects took {ratio:.1}x as long to write ({a:?} → {b:?})" + ); +} From 1a429fcfa77098ea92c8985a305f69ae321bbee3 Mon Sep 17 00:00:00 2001 From: Cihad GUNDOGDU Date: Tue, 24 Nov 2026 16:12:05 +0300 Subject: [PATCH 2/2] Gather the dictionaries' owners once per DXF write The writer asked CadDocument::extension_dictionary_handle for every table record, and for a record naming no extension dictionary the lookup walked every object of the document: quadratic in records times objects. The writer now gathers each dictionary's owner once (CadDocument::owned_dictionaries, first match in the objects' order, as the walk's find_map) and answers the walk's step from it; the lookup's other steps are shared, not copied, and extension_dictionary_handle itself is unchanged. tests/dxf_write_scaling.rs: ratio 14.2 -> 4.1 (debug). A 32 MB DWG (507 811 objects, 16 027 block records) written to DXF in a release build: 112.3 s -> 2.95 s. Closes #651 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GBAJR1pu3dhJEV6kKtxAfp --- CHANGELOG.md | 7 ++++ src/document.rs | 62 ++++++++++++++++++++++++----- src/io/dxf/writer/mod.rs | 1 + src/io/dxf/writer/section_writer.rs | 25 +++++++++++- 4 files changed, 83 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7354051e..6b57b3a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ### Unreleased +- **DXF writer looks extension dictionaries up in linear time** - Each table + record that names no extension dictionary had its owner looked up by walking + every object of the document, so writing a DXF was quadratic in block records + times objects (a 32 MB DWG with 16 027 block records took 11.3 s to write). + The writer now gathers the dictionaries' owners once per write + (`CadDocument::owned_dictionaries`); `extension_dictionary_handle` is + unchanged. - **Extended dimensions keep AcDbDimension base groups** - The ARC_DIMENSION and LARGE_RADIAL_DIMENSION reader had no arms for the AcDbDimension insertion point (12), horizontal direction (51) and diff --git a/src/document.rs b/src/document.rs index 9f32d265..da6d1f16 100644 --- a/src/document.rs +++ b/src/document.rs @@ -4551,6 +4551,57 @@ impl CadDocument { } pub fn extension_dictionary_handle(&self, owner: Handle) -> Option { + self.extension_dictionary_handle_or(owner, || { + self.objects + .iter() + .find_map(|(handle, object)| match object { + ObjectType::Dictionary(dictionary) + if dictionary.owner == owner && !handle.is_null() => + { + Some(*handle) + } + _ => None, + }) + }) + } + + /// [`Self::extension_dictionary_handle`] with its last step, the walk over + /// every object for a dictionary `owner` owns, answered from `owned` + /// ([`Self::owned_dictionaries`]). For a caller that asks for many owners + /// while the document does not change: the DXF writer asks for every + /// table record, and walking every object each time made writing + /// quadratic in records times objects. + pub(crate) fn extension_dictionary_handle_in( + &self, + owner: Handle, + owned: &HashMap, + ) -> Option { + self.extension_dictionary_handle_or(owner, || owned.get(&owner).copied()) + } + + /// Each owner of a dictionary and that dictionary, the first one in the + /// order of `objects` for an owner of several: what the walk in + /// [`Self::extension_dictionary_handle`] finds for each owner, gathered in + /// one walk. + pub(crate) fn owned_dictionaries(&self) -> HashMap { + let mut owned = HashMap::new(); + for (handle, object) in &self.objects { + if let ObjectType::Dictionary(dictionary) = object { + if !handle.is_null() { + owned.entry(dictionary.owner).or_insert(*handle); + } + } + } + owned + } + + /// The steps of [`Self::extension_dictionary_handle`] before its walk over + /// every object, which `walk` takes. + fn extension_dictionary_handle_or( + &self, + owner: Handle, + walk: impl FnOnce() -> Option, + ) -> Option { // A record without a handle owns nothing; the search below would // otherwise return the root dictionary, whose owner is NULL too. if owner.is_null() { @@ -4585,16 +4636,7 @@ impl CadDocument { if matches!(self.objects.get(&owner), Some(ObjectType::Dictionary(_))) { return None; } - self.objects - .iter() - .find_map(|(handle, object)| match object { - ObjectType::Dictionary(dictionary) - if dictionary.owner == owner && !handle.is_null() => - { - Some(*handle) - } - _ => None, - }) + walk() } /// Resolve a named XRecord in `owner`'s extension dictionary. diff --git a/src/io/dxf/writer/mod.rs b/src/io/dxf/writer/mod.rs index 18ef3e93..ee9bcd23 100644 --- a/src/io/dxf/writer/mod.rs +++ b/src/io/dxf/writer/mod.rs @@ -395,6 +395,7 @@ impl<'a> DxfWriter<'a> { let mut section_writer = SectionWriter::new(writer, handle_start, handle_seed); section_writer.set_version(output_version); section_writer.build_valid_handles(document); + section_writer.gather_owned_dictionaries(document); if let Some(counts) = class_counts { section_writer.set_class_instance_counts(counts); } diff --git a/src/io/dxf/writer/section_writer.rs b/src/io/dxf/writer/section_writer.rs index ca87e86f..45c28923 100644 --- a/src/io/dxf/writer/section_writer.rs +++ b/src/io/dxf/writer/section_writer.rs @@ -102,6 +102,11 @@ pub struct SectionWriter<'a, W: DxfStreamWriter> { /// Records written per DXF name (upper case), used for the CLASSES /// instance counts. `None` keeps each class's stored count. class_instance_counts: Option>, + /// Each dictionary's owner in the document being written + /// (`CadDocument::owned_dictionaries`), gathered once: every table record + /// is asked for its extension dictionary. `None` walks the document's + /// objects for each record. + owned_dictionaries: Option>, } impl<'a, W: DxfStreamWriter> SectionWriter<'a, W> { @@ -128,6 +133,22 @@ impl<'a, W: DxfStreamWriter> SectionWriter<'a, W> { loft_reference_appid: None, source_dwg_context: None, class_instance_counts: None, + owned_dictionaries: None, + } + } + + /// Gather the dictionaries' owners of `document` once, for the extension + /// dictionaries of its table records. The document must not change while + /// this writer writes it. + pub(crate) fn gather_owned_dictionaries(&mut self, document: &CadDocument) { + self.owned_dictionaries = Some(document.owned_dictionaries()); + } + + /// `owner`'s extension dictionary, from the gathered owners when there are. + fn extension_dictionary(&self, document: &CadDocument, owner: Handle) -> Option { + match &self.owned_dictionaries { + Some(owned) => document.extension_dictionary_handle_in(owner, owned), + None => document.extension_dictionary_handle(owner), } } @@ -2085,7 +2106,7 @@ impl<'a, W: DxfStreamWriter> SectionWriter<'a, W> { self.writer.write_string(0, "TABLE")?; self.writer.write_string(2, name)?; self.writer.write_handle(5, table_handle)?; - if let Some(handle) = document.extension_dictionary_handle(table_handle) { + if let Some(handle) = self.extension_dictionary(document, table_handle) { self.writer.write_string(102, "{ACAD_XDICTIONARY")?; self.writer.write_handle(360, handle)?; self.writer.write_string(102, "}")?; @@ -2107,7 +2128,7 @@ impl<'a, W: DxfStreamWriter> SectionWriter<'a, W> { handle: Handle, document: &CadDocument, ) -> Result<()> { - if let Some(xdictionary) = document.extension_dictionary_handle(handle) { + if let Some(xdictionary) = self.extension_dictionary(document, handle) { if !xdictionary.is_null() && (self.valid_handles.is_empty() || self.valid_handles.contains(&xdictionary)) {