Rust是否会优化计算范围内的循环? [英] Does Rust optimize for loops over calculated ranges?

查看:84
本文介绍了Rust是否会优化计算范围内的循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为练习,我试图对Rust 1.3.0中的代码进行微优化.我有一个遍历数组的循环.像这样:

As an exercise I'm trying to micro-optimize code in Rust 1.3.0. I have a loop of a loop over an array. Something like this:

loop {
    for i in 0..arr.len() {
        // something happens here
    }
}

由于数组在Rust中是固定大小的,编译器会通过只评估一次arr.len()并重用该值来优化代码,还是会在顶层循环的每次遍历中对表达式进行评估?除了arr.len()之外,这个问题可以扩展为更多无副作用的繁琐计算功能.

Since arrays are fixed size in Rust, will the compiler optimize the code by evaluating arr.len() just once and reusing the value, or will the expression be evaluated with each pass of the top-level loop? The question can be expanded to more calculation-heavy functions without side-effects, other than arr.len().

换句话说,上面的代码是否等效于此:

In other words, would the above code be equivalent to this:

let arr_len = arr.len();

loop {
    for i in 0..arr_len {
        // something happens here
    }
}

推荐答案

..是范围运算符,形成

The .. is a range operator, which forms a Range<Idx> object (or a derivative: RangeFrom, RangeFull or RangeTo). Those objects only contain indexes (the Idx type), so you can rest assured that .len() is only evaluated once.

通常,检查LLVM IR是一个好主意.如果您有一个综合示例,则可以轻松地使用游乐场.对于示例:

In general, it is a good idea to inspect the LLVM IR. If you have a synthetic example, you can use the playground easily enough. For example:

// A black-box prevents optimization, and its calls are easy to spot.
extern {
    fn doit(i: i32) -> ();
}

fn main() {
    let arr = [1, 2, 3, 4, 5];

    for i in 0..arr.len() {
        unsafe { doit(arr[i]); }
    }
}

具有以下功能:

; Function Attrs: uwtable
define internal void @_ZN4main20hd87dea49c835fe43laaE() unnamed_addr #1 {
entry-block:
  tail call void @doit(i32 1)
  tail call void @doit(i32 2)
  tail call void @doit(i32 3)
  tail call void @doit(i32 4)
  tail call void @doit(i32 5)
  ret void
}

在这种情况下,长度固定,根本没有循环:它已经展开.

In this case, with a fixed length, there is no loop at all: it has been unrolled.

这篇关于Rust是否会优化计算范围内的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆