Created
May 16, 2021 23:00
-
-
Save sbeyer/4e63143e78ac38cb06475635c0575bf9 to your computer and use it in GitHub Desktop.
For loop vs map in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(test)] | |
extern crate test; | |
use std::net::*; | |
pub struct Foo { | |
a: u8, | |
b: u8, | |
c: u8, | |
d: u8, | |
} | |
impl Foo { | |
fn addr(self) -> Ipv4Addr { | |
Ipv4Addr::new(self.a, self.b, self.c, self.d) | |
} | |
} | |
pub fn with_for(ip_addresses: Vec<Foo>) -> Vec<IpAddr> { | |
let mut result: Vec<IpAddr> = vec![]; // Vec::with_capacity(ip_addresses.len()); | |
for ip_address in ip_addresses.into_iter() { | |
result.push(IpAddr::V4(ip_address.addr())); | |
} | |
result | |
} | |
pub fn with_map(ip_addresses: Vec<Foo>) -> Vec<IpAddr> { | |
ip_addresses | |
.into_iter() | |
.map(|ip_address| IpAddr::V4(ip_address.addr())) | |
.collect() | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
use test::Bencher; | |
fn prepare() -> Vec<Foo> { | |
(1..=255) | |
.into_iter() | |
.map(|d| Foo { | |
a: 127, | |
b: 0, | |
c: 0, | |
d, | |
}) | |
.collect() | |
} | |
#[bench] | |
fn bench_with_for(b: &mut Bencher) { | |
b.iter(|| with_for(prepare())); | |
} | |
#[bench] | |
fn bench_with_map(b: &mut Bencher) { | |
b.iter(|| with_map(prepare())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ty for sharing