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 <mrobinson@igalia.com>
This commit is contained in:
Jonathan Schwender 2025-06-23 11:23:07 +02:00 committed by GitHub
parent 5e252d0ef6
commit cd30b78f78
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -517,10 +517,6 @@ pub fn write_json_to_file<T>(data: &T, config_dir: &Path, filename: &str)
where where
T: Serialize, 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 path = config_dir.join(filename);
let display = path.display(); let display = path.display();
@ -529,10 +525,8 @@ where
Ok(file) => file, Ok(file) => file,
}; };
match file.write_all(json_encoded.as_bytes()) { serde_json::to_writer_pretty(&mut file, data).expect("Could not serialize to file");
Err(why) => panic!("couldn't write to {}: {}", display, why), trace!("successfully wrote to {display}");
Ok(_) => trace!("successfully wrote to {}", display),
}
} }
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]