From cd30b78f78a05ea8f3db72351b14df7a885b3d70 Mon Sep 17 00:00:00 2001 From: Jonathan Schwender <55576758+jschwe@users.noreply.github.com> Date: Mon, 23 Jun 2025 11:23:07 +0200 Subject: [PATCH] resource_thread: Optimize writing JSON (#37628) Instead of serializing everything at once in memory it is more efficient to use `to_writer_pretty`. The memory allocations from writing the HSTS file to disk showed up very visibly in DHAT and should be fixed by streaming the writing. This change should reduce allocations. Testing: This change should not modify behavior, and thus is covered by existing tests. --------- Signed-off-by: Jonathan Schwender <55576758+jschwe@users.noreply.github.com> Co-authored-by: Martin Robinson --- components/net/resource_thread.rs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/components/net/resource_thread.rs b/components/net/resource_thread.rs index 5572d8c7cc1..058702d2663 100644 --- a/components/net/resource_thread.rs +++ b/components/net/resource_thread.rs @@ -517,10 +517,6 @@ pub fn write_json_to_file(data: &T, config_dir: &Path, filename: &str) where T: Serialize, { - let json_encoded: String = match serde_json::to_string_pretty(&data) { - Ok(d) => d, - Err(_) => return, - }; let path = config_dir.join(filename); let display = path.display(); @@ -529,10 +525,8 @@ where Ok(file) => file, }; - match file.write_all(json_encoded.as_bytes()) { - Err(why) => panic!("couldn't write to {}: {}", display, why), - Ok(_) => trace!("successfully wrote to {}", display), - } + serde_json::to_writer_pretty(&mut file, data).expect("Could not serialize to file"); + trace!("successfully wrote to {display}"); } #[derive(Clone, Debug, Deserialize, Serialize)]