代码之家  ›  专栏  ›  技术社区  ›  kbec

编译器可以对trait的方法进行默认实现的内联吗?

  •  0
  • kbec  · 技术社区  · 6 年前

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

    我需要重写整个方法体并用 #[inline] 当实现trait for type而不是像上面那样仅仅标记trait的方法时?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Jmb    6 年前

    如果我理解正确的话,你问的是两件事:

    • magnitude ?
    • square_magnitude 里面 震级 它本身是声明的 inline 平方μ震级

    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()
    }
    

    用rustcv1.28.0和option编译 -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
    
    推荐文章