Home > other >  Which one is faster x =x or x*=2
Which one is faster x =x or x*=2

Time:10-03

I recently make a program to make an image of the Mandelbrot set. To do this is I have written a function which returns if a point is a point of Mandelbrot set. And in this function I found 2 ways to do my calculation:

let temp=a;
a=a*a-b*b x;
b=2.0*b*temp y;

or

let temp=a;
a=a*a-b*b x;
b*=temp;
b =b y;

Which one is faster if there is a faster one? (I use rust language if this changes something)?

CodePudding user response:

I've put both your codes into the playground, as a public functions (assuming that your values are all floats, but this shouldn't make any real diference):

pub fn mult(mut a: f32, mut b: f32, x: f32, y: f32) -> f32 {
    let temp = a;
    a = a * a - b * b   x;
    b = 2.0 * b * temp   y;
    b
}

pub fn add(mut a: f32, mut b: f32, x: f32, y: f32) -> f32 {
    let temp = a;
    a = a * a - b * b   x;
    b *= temp;
    b  = b   y;
    b
}

The assembly generated in release mode is almost identical (just reordered):

playground::mult:
    addss   xmm1, xmm1
    mulss   xmm0, xmm1
    addss   xmm0, xmm3
    ret

playground::add:
    mulss   xmm0, xmm1
    addss   xmm3, xmm0
    addss   xmm0, xmm3
    ret

So, there should be no measurable difference. However, if you're worried, you should benchmark your real case to see whether some of these approaches leads to missing optimizations in the larger picture.

  • Related