Skip to content

Commit d132ddd

Browse files
authored
perf: optimize string handling in open() method using Cow<str> (#5)
- Replace unnecessary .to_string() and .clone() calls with Cow<str> - Avoid memory allocations in shm_open and flink modes by borrowing existing strings - Only allocate memory when necessary (tmpfs mode) - Improves performance in high-frequency scenarios
1 parent ccd7d34 commit d132ddd

1 file changed

Lines changed: 5 additions & 4 deletions

File tree

src/lib.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
//!
33
//! For help on how to get started, take a look at the [examples](https://github.com/elast0ny/shared_memory-rs/tree/master/examples) !
44
5+
use std::borrow::Cow;
56
use std::fs::{File, OpenOptions};
67
use std::io::{ErrorKind, Read, Write};
78

@@ -275,15 +276,15 @@ impl ShmemConf {
275276
let mut retry = 0;
276277

277278
loop {
278-
let target_identifier = if let Some(ref unique_id) = self.os_id {
279+
let target_identifier: Cow<str> = if let Some(ref unique_id) = self.os_id {
279280
retry = 5;
280281
if cfg!(not(target_os = "windows")) && self.use_tmpfs {
281282
// tmpfs mode: convert os_id to file path
282283
let tmpfs_path = self.get_tmpfs_file_path()?;
283-
tmpfs_path.to_string_lossy().to_string()
284+
Cow::Owned(tmpfs_path.to_string_lossy().into_owned())
284285
} else {
285286
// shm_open mode: use os_id directly
286-
unique_id.clone()
287+
unique_id.as_str().into()
287288
}
288289
} else if let Some(ref flink_path) = self.flink_path {
289290
// Read from flink file
@@ -295,7 +296,7 @@ impl ShmemConf {
295296
flink_content.clear();
296297
f.read_to_string(&mut flink_content)
297298
.map_err(ShmemError::LinkReadFailed)?;
298-
flink_content.clone()
299+
flink_content.as_str().into()
299300
} else {
300301
return Err(ShmemError::NoLinkOrOsId);
301302
};

0 commit comments

Comments
 (0)