rust听说非常的牛逼。
就尝试了一下,找了一个web server 的小demo。
具体代码见下,在编译时发现
cargo build --release的时候,生成的release的二进制程序跟debug的程序一样大。
file看了一下有debug_info
file target/release/hello
target/release/hello: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=478ff8955688b981a585603b4ab47a2930c6a994, for GNU/Linux 3.2.0, with debug_info, not stripped
于是就搜了一下,在 Cargo.toml中添加一个配置就可以将二进制程序瘦身。
[profile.release]
strip = true
可以看到瘦身后只有355K,之前可以有13MB的。 确实效果非常显著。
ll -h ./target/release/hello
-rwxrwxr-x 2 pcl pcl 355K 1月 30 17:51 ./target/release/hello*
具体过程:
cargo new hellocd hello
src/main.rs
use std::{fs,io::{prelude::*, BufReader},net::{TcpListener, TcpStream},
};fn main() {let listener = TcpListener::bind("127.0.0.1:7878").unwrap();for stream in listener.incoming() {let stream = stream.unwrap();handle_connection(stream);}
}fn handle_connection(mut stream: TcpStream) {let buf_reader = BufReader::new(&mut stream);let http_request: Vec<_> = buf_reader.lines().map(|result| result.unwrap()).take_while(|line| !line.is_empty()).collect();let status_line = "HTTP/1.1 200 OK";let contents = fs::read_to_string("hello.html").unwrap();let length = contents.len();let response =format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");stream.write_all(response.as_bytes()).unwrap();
}
本地目录下hello.html
<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><title>Hello!</title></head><body><h1>Hello!</h1><p>Hi from Rust</p></body>
</html>
Cargo.toml
[package]
name = "hello"
version = "0.1.0"
edition = "2021"# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html[dependencies][profile.release]
strip = true