Skip to main content
5 of 5
replaced http://stackoverflow.com/ with https://stackoverflow.com/

You're doing two tests to compare p1.x with p2.x:

  • One here: int x = (int) (dx < 0 ? p2.x : p1.x);
  • Another here (implicit in the Math.abs method): int w = (int) Math.abs(dx);

You also have the overhead of making a subroutine call to Math.abs.

Faster would be:

if (p1.x <= p2.x)
{
    int x = p1.x;
    int w = p2.x - p1.x;
    if (p1.y <= p2.y)
    {
        int y = p1.y;
        int h = p2.y - p1.y;
        return new Rectangle(x, y, w, h);
    }
    else
    {
        int y = p2.y;
        int h = p1.y - p2.y;
        return new Rectangle(x, y, w, h);
    }
}
else
{
    ... etc ...
}

Refactoring the above to reduce duplication:

int x;
int w;
if (p1.x <= p2.x)
{
    x = p1.x;
    w = p2.x - p1.x;
}
else
{
    x = p2.x;
    w = p1.x - p2.x;
}
int y;
int h;
if (p1.y <= p2.y)
{
    y = p1.y;
    h = p2.y - p1.y;
}
else
{
    y = p2.y;
    h = p1.y - p2.y;
}
return new Rectangle(x, y, w, h);

Or refactoring to make it more compact:

if (p1.x <= p2.x)
{
    if (p1.y <= p2.y)
    {
        return new Rectangle(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
    }
    else
    {
        return new Rectangle(p1.x, p2.y, p2.x - p1.x, p1.y - p2.y);
    }
}
else
{
    ... etc ...
}

If you want to implement rolfl's suggestion to have the bounding rectangle outside the points, then use Math.ceil for example:

if (p1.x <= p2.x)
{
    int x = p1.x;
    int w = Math.ceil(p2.x) - x;
    ... etc ...
ChrisW
  • 12.9k
  • 1
  • 34
  • 76