Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is algorithm so slow?

I'm creating a line graph, and the code I originally used was so slow at drawing that it was useless. I replaced it with code I found online and it became much faster. I was just curious as to why the original code is so slow. All of the code posted below is inside the onDraw() method of a custom view:

Original slow code:

    float yStart = 300f;

    for (int i=0; i < values.length; i++){              

        drawPath.moveTo(xStart, yStart);
        drawPath.lineTo(xStart+10, values[i]);
        drawPath.close();
        canvas.drawPath(drawPath, linePaint);

        xStart += 10;
        yStart = values[i]; 
    }

Later fast code:

            float datalength = values.length;
            float colwidth = (width - (2 * border)) / datalength;
            float halfcol = colwidth / 2;
            float lasth = 0;                
            for (int i = 0; i < values.length; i++) {
                float val = values[i] - min;
                float rat = val / diff;
                float h = graphHeight * rat;
                if (i > 0)
                    canvas.drawLine(((i - 1) * colwidth) + (horStart + 1) + halfcol, (border - lasth) + graphHeight, (i * colwidth) + (horStart + 1) + halfcol, (border - h) + graphHeight, linePaint);
                lasth = h;

I just don't understand why one is so much more efficient than the other. Any ideas?

like image 316
user650309 Avatar asked Jul 16 '26 07:07

user650309


2 Answers

It is CLEAR

In the first piece, there are three operations on objects {moveTo, lineTo, drawPath, and close}


Int the second piece, it is all float operations except one operation on objects

like image 195
Sherif elKhatib Avatar answered Jul 17 '26 21:07

Sherif elKhatib


Using Paths makes the drawing significantly slower than simply telling the Canvas to draw a straight line between two points since Path is a much more complex object than the 2 points that drawLine() uses. Paths are also filled and framed based on the Style in the Paint which could also cause a slowdown.

In general, using objects and calling a lot of methods in a loop slows down your code.

like image 38
tskuzzy Avatar answered Jul 17 '26 20:07

tskuzzy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!