bench_vs_lazy_static.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. use lazy_static::lazy_static;
  2. use once_cell::sync::Lazy;
  3. const N_THREADS: usize = 32;
  4. const N_ROUNDS: usize = 100_000_000;
  5. static ONCE_CELL: Lazy<Vec<String>> = Lazy::new(|| vec!["Spica".to_string(), "Hoyten".to_string()]);
  6. lazy_static! {
  7. static ref LAZY_STATIC: Vec<String> = vec!["Spica".to_string(), "Hoyten".to_string()];
  8. }
  9. fn main() {
  10. let once_cell = {
  11. let start = std::time::Instant::now();
  12. let threads = (0..N_THREADS)
  13. .map(|_| std::thread::spawn(move || thread_once_cell()))
  14. .collect::<Vec<_>>();
  15. for thread in threads {
  16. thread.join().unwrap();
  17. }
  18. start.elapsed()
  19. };
  20. let lazy_static = {
  21. let start = std::time::Instant::now();
  22. let threads = (0..N_THREADS)
  23. .map(|_| std::thread::spawn(move || thread_lazy_static()))
  24. .collect::<Vec<_>>();
  25. for thread in threads {
  26. thread.join().unwrap();
  27. }
  28. start.elapsed()
  29. };
  30. println!("once_cell: {:?}", once_cell);
  31. println!("lazy_static: {:?}", lazy_static);
  32. }
  33. fn thread_once_cell() {
  34. for _ in 0..N_ROUNDS {
  35. let len = ONCE_CELL.len();
  36. assert_eq!(len, 2)
  37. }
  38. }
  39. fn thread_lazy_static() {
  40. for _ in 0..N_ROUNDS {
  41. let len = LAZY_STATIC.len();
  42. assert_eq!(len, 2)
  43. }
  44. }