TcpStream startup performance[solved]



I’ve building a tool that opens many sockets. I noticed that the performance of TcpStream::Connect(address) varies greatly depending on how it receives the address argument. Note, this is only measuring opening a socket (I think).


use std::io::{Read, Write};
use std::net::lookup_host;
use std::net::TcpStream;
use std::thread;
use std::time::{Duration, Instant};

pub fn main() { 
    let mut handles = Vec::new();

    for i in 0..300 { 
        let ip = lookup_host("").unwrap().take(1).next().unwrap().unwrap().ip();
        //let ip = "";
        //let ip = "";
        let port = 80;

        let handle = thread::spawn(move || { 

            let time_start = Instant::now();
            let mut stream = TcpStream::connect((ip, port)).unwrap();
            let elapsed_time = time_start.elapsed();
            println!("socket Time from thread {} start to tcpstream start: {}", i, elapsed_time.as_secs());

    for handle in handles { 

Doing a host lookup on every iteration actually has the fastest TcpStream startup (300 sockets within 1 second).

Passing a &str is somewhat slower (300 sockets up to 3 seconds), and passing in the hostname (which then does the lookup inside TcpStream::connect()?) is very slow, with pauses of 5 seconds every now and then and taking up to 15 seconds.

Does anybody else see this behavior? I think the oddest thing is that a host lookup is consistently faster than checking if an &str is a valid ip address.

Edit: python has similar behavior, so perhaps it’s a Linux socket thing.

Edit: So, of course I was being silly, and the time measured did not include Host lookup. So, to me that means that submitting the address as and IpAddr is faster than as a &str.