【问题标题】:Can compiler do a default implementation's inlining of the trait's method?编译器可以对特征方法进行默认实现的内联吗?
【发布时间】:2018-09-02 21:15:12
【问题描述】:

我知道 trait 的方法没有主体,所以没有什么可内联的。但是这样标记它的默认实现有什么意义吗?

trait Magnitude {
    fn square_magnitude( &self ) -> f64;

    #[inline]
    fn magnitude( &self ) -> f64 {
        self.square_magnitude().sqrt()
    }
}

在实现类型的 trait 时是否需要重写整个方法体并用 #[inline] 标记这个 impl 的方法,而不是像上面那样只标记 trait 的方法?

【问题讨论】:

标签: rust inline traits default-implementation


【解决方案1】:

如果我正确理解了这个问题,那么您在问两件事:

  • 编译器会内联调用magnitude吗?
  • 如果square_magnitude 本身声明为inline,即使square_magnitude 的代码在特征中不可用,编译器是否能够内联对square_magnitude 的调用?

至于第一个,它没有理由不能。至于第二个答案是肯定的,编译器将能够内联这两个函数,因为在它生成代码时,这两个函数的源代码都是可用的。这可以在disassembly看到:

trait Magnitude {
    fn square_magnitude( &self ) -> f64;

    #[inline]
    fn magnitude( &self ) -> f64 {
        self.square_magnitude().sqrt()
    }
}

struct Vector { x: f64, y: f64 }

impl Magnitude for Vector {
    #[inline]
    fn square_magnitude (&self) -> f64 {
        self.x*self.x + self.y*self.y
    }
}

pub fn test (x: f64, y: f64) -> f64 {
    let v = Vector { x: x, y: y };
    v.magnitude()
}

使用 rustc v1.28.0 和选项 -O 编译:

example::test:
        mulsd   xmm0, xmm0
        mulsd   xmm1, xmm1
        addsd   xmm1, xmm0
        xorps   xmm0, xmm0
        sqrtsd  xmm0, xmm1
        ret

但请注意,compiler will not inline square_magnitude inside magnitude if square_magnitude is not declared inline itself:

impl Magnitude for Vector {
    fn square_magnitude (&self) -> f64 {
        self.x*self.x + self.y*self.y
    }
}

生成:

<example::Vector as example::Magnitude>::square_magnitude:
        movsd   xmm1, qword ptr [rdi]
        movsd   xmm0, qword ptr [rdi + 8]
        mulsd   xmm1, xmm1
        mulsd   xmm0, xmm0
        addsd   xmm0, xmm1
        ret

example::test:
        mulsd   xmm0, xmm0
        mulsd   xmm1, xmm1
        addsd   xmm1, xmm0
        xorps   xmm0, xmm0
        sqrtsd  xmm0, xmm1
        ret

【讨论】:

    猜你喜欢
    • 2021-04-04
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多