Why should I use Cargo if “cargo build” is slower than running rustc directly?

不问归期 提交于 2019-12-23 05:22:36

问题


I created a simple hello world program:

fn main() {
    println!("Hello, world");
}

When compiling the code using rustc vs cargo build, the cargo command appears slower. It takes 1.6s for cargo build vs 1s for rustc. See the timestamps on the right in the screenshot.

Why is this? Why should I still use cargo?


回答1:


As Pavel Strakhov said

Cargo is not a compiler, it's a package manager. It runs rustc and does some extra work (e.g. resolves dependencies), so it can't be faster than bare rustc.

You can see this for yourself by running cargo build --verbose, which outputs the rustc command that cargo runs:

$ cargo build --verbose
   Compiling hw v0.1.0 (file:///private/tmp/hw)
     Running `rustc --crate-name hw src/main.rs --crate-type bin --emit=dep-info,link -C debuginfo=2 -C metadata=3c693c67d55ff970 -C extra-filename=-3c693c67d55ff970 --out-dir /private/tmp/hw/target/debug/deps -L dependency=/private/tmp/hw/target/debug/deps`
    Finished dev [unoptimized + debuginfo] target(s) in 0.30 secs

Why should I still use cargo

The output above shows one reason: Look at all those arguments passed to rustc. Do you know what each of them does? Do you want to know? Cargo abstracts some of the details away, allowing you to concentrate on the code.

Cargo also does so much more than just invoking the compiler. The biggest benefit to most people is that it manages your dependencies based on versions and allows publishing your own crates as well. It also allows for build scripts which run before your main compilation. It has easy ways of running your tests and examples.

More immediately useful, Cargo performs a check to see if you should rebuild at all:

$ time rustc src/main.rs
0:00.21
$ time rustc src/main.rs
0:00.22

$ time cargo build
0:00.41
$ time cargo build
0:00.09                   # Much better!


来源:https://stackoverflow.com/questions/44483749/why-should-i-use-cargo-if-cargo-build-is-slower-than-running-rustc-directly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!