Skip to content

Instantly share code, notes, and snippets.

@sbeyer
Created May 16, 2021 23:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbeyer/4e63143e78ac38cb06475635c0575bf9 to your computer and use it in GitHub Desktop.
Save sbeyer/4e63143e78ac38cb06475635c0575bf9 to your computer and use it in GitHub Desktop.
For loop vs map in Rust
#![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()));
}
}
@evoxmusic
Copy link

ty for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment