Avoid some format! into immediate format! (#2913)

# Objective

- Avoid usages of `format!` that ~immediately get passed to another `format!`. This avoids a temporary allocation and is just generally cleaner.

## Solution

- `bevy_derive::shader_defs` does a `format!("{}", val.to_string())`, which is better written as just `format!("{}", val)`
- `bevy_diagnostic::log_diagnostics_plugin` does a `format!("{:>}", format!(...))`, which is better written as `format!("{:>}", format_args!(...))`
- `bevy_ecs::schedule` does `tracing::info!(..., name = &*format!("{:?}", val))`, which is better written with the tracing shorthand `tracing::info!(..., name = ?val)`
- `bevy_reflect::reflect` does `f.write_str(&format!(...))`, which is better written as `write!(f, ...)` (this could also be written using `f.debug_tuple`, but I opted to maintain alt debug behavior)
- `bevy_reflect::serde::{ser, de}` do `serde::Error::custom(format!(...))`, which is better written as `Error::custom(format_args!(...))`, as `Error::custom` takes `impl Display` and just immediately calls `format!` again
This commit is contained in:
Christopher Durham 2021-10-06 18:34:33 +00:00
parent 07ed1d053e
commit a60fe30ada
6 changed files with 19 additions and 15 deletions

View file

@ -31,7 +31,7 @@ pub fn derive_shader_defs(input: TokenStream) -> TokenStream {
let struct_name_pascal_case = ast.ident.to_string().to_pascal_case(); let struct_name_pascal_case = ast.ident.to_string().to_pascal_case();
let shader_defs = shader_def_idents let shader_defs = shader_def_idents
.iter() .iter()
.map(|i| format!("{}_{}", struct_name_pascal_case, i.to_string()).to_uppercase()); .map(|i| format!("{}_{}", struct_name_pascal_case, i).to_uppercase());
let shader_defs_len = shader_defs.len(); let shader_defs_len = shader_defs.len();
let shader_def_indices = 0..shader_defs_len; let shader_def_indices = 0..shader_defs_len;

View file

@ -56,22 +56,24 @@ impl LogDiagnosticsPlugin {
if let Some(average) = diagnostic.average() { if let Some(average) = diagnostic.average() {
info!( info!(
target: "bevy diagnostic", target: "bevy diagnostic",
"{:<name_width$}: {:>12} (avg {:>})",
diagnostic.name,
// Suffix is only used for 's' as in seconds currently, // Suffix is only used for 's' as in seconds currently,
// so we reserve one column for it // so we reserve one column for it; however,
format!("{:.6}{:1}", value, diagnostic.suffix),
// Do not reserve one column for the suffix in the average // Do not reserve one column for the suffix in the average
// The ) hugging the value is more aesthetically pleasing // The ) hugging the value is more aesthetically pleasing
format!("{:.6}{:}", average, diagnostic.suffix), "{name:<name_width$}: {value:>11.6}{suffix:1} (avg {average:>.6}{suffix:})",
name = diagnostic.name,
value = value,
suffix = diagnostic.suffix,
average = average,
name_width = crate::MAX_DIAGNOSTIC_NAME_WIDTH, name_width = crate::MAX_DIAGNOSTIC_NAME_WIDTH,
); );
} else { } else {
info!( info!(
target: "bevy diagnostic", target: "bevy diagnostic",
"{:<name_width$}: {:>}", "{name:<name_width$}: {value:>.6}{suffix:}",
diagnostic.name, name = diagnostic.name,
format!("{:.6}{:}", value, diagnostic.suffix), value = value,
suffix = diagnostic.suffix,
name_width = crate::MAX_DIAGNOSTIC_NAME_WIDTH, name_width = crate::MAX_DIAGNOSTIC_NAME_WIDTH,
); );
} }

View file

@ -334,8 +334,7 @@ impl Schedule {
pub fn run_once(&mut self, world: &mut World) { pub fn run_once(&mut self, world: &mut World) {
for label in self.stage_order.iter() { for label in self.stage_order.iter() {
#[cfg(feature = "trace")] #[cfg(feature = "trace")]
let stage_span = let stage_span = bevy_utils::tracing::info_span!("stage", name = ?label);
bevy_utils::tracing::info_span!("stage", name = &format!("{:?}", label) as &str);
#[cfg(feature = "trace")] #[cfg(feature = "trace")]
let _stage_guard = stage_span.enter(); let _stage_guard = stage_span.enter();
let stage = self.stages.get_mut(label).unwrap(); let stage = self.stages.get_mut(label).unwrap();

View file

@ -49,7 +49,7 @@ pub unsafe trait Reflect: Any + Send + Sync {
impl Debug for dyn Reflect { impl Debug for dyn Reflect {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&format!("Reflect({})", self.type_name())) write!(f, "Reflect({})", self.type_name())
} }
} }

View file

@ -200,11 +200,14 @@ impl<'a, 'de> Visitor<'de> for ReflectVisitor<'a> {
.ok_or_else(|| de::Error::missing_field(type_fields::TYPE))?; .ok_or_else(|| de::Error::missing_field(type_fields::TYPE))?;
let registration = let registration =
self.registry.get_with_name(&type_name).ok_or_else(|| { self.registry.get_with_name(&type_name).ok_or_else(|| {
de::Error::custom(format!("No registration found for {}", type_name)) de::Error::custom(format_args!(
"No registration found for {}",
type_name
))
})?; })?;
let deserialize_reflect = let deserialize_reflect =
registration.data::<ReflectDeserialize>().ok_or_else(|| { registration.data::<ReflectDeserialize>().ok_or_else(|| {
de::Error::custom(format!( de::Error::custom(format_args!(
"The TypeRegistration for {} doesn't have DeserializeReflect", "The TypeRegistration for {} doesn't have DeserializeReflect",
type_name type_name
)) ))

View file

@ -23,7 +23,7 @@ impl<'a> Serializable<'a> {
fn get_serializable<E: serde::ser::Error>(reflect_value: &dyn Reflect) -> Result<Serializable, E> { fn get_serializable<E: serde::ser::Error>(reflect_value: &dyn Reflect) -> Result<Serializable, E> {
reflect_value.serializable().ok_or_else(|| { reflect_value.serializable().ok_or_else(|| {
serde::ser::Error::custom(&format!( serde::ser::Error::custom(format_args!(
"Type '{}' does not support ReflectValue serialization", "Type '{}' does not support ReflectValue serialization",
reflect_value.type_name() reflect_value.type_name()
)) ))