Executing SQL queries in loop induced unnecessary network transfert, calculation by the cpu and RAM usage.

Non compliant Code Example

public function foo() {
    ...
    $baseQuery = "SELECT name FROM users where id = ";

    for ($i = 0; $i < 20; ++$i) {

        $query = $baseQuery . $i;
        $connection = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
            mysql_select_db($dbname) or die("Could not open the db '$dbname'");
        $result = mysql_query($this->Query);// Noncompliant

        // iterate through the result
        ...
        mysql_close($connection);
    }
    ...
}

Compliant Solution

public function foo() {
    ...
    $query = "SELECT name FROM users where id in (";

    for ($i = 0; $i < 20; ++$i) {
        $query .= ',' . $i;
    }
    $query .= ')';

    $connection = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
    mysql_select_db($dbname) or die("Could not open the db '$dbname'");
    $result = mysql_query($this->Query); // compliant

    // iterate through the result
    ...
    mysql_close($connection);
}

The three sources of impacts of a code identified are:

  • Energy: measured in joules (J)

  • Transfer: measured in Bytes (B)

  • Storage: measured in Bytes (B)

The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption.

The ETSdiff tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment).

The results generated by ETSdiff must help define the interest of the rule reported by SonarQube in the context of the code analyzed.

Case for a 1GB database:

ETSdiff percent comparison" style="padding: 1rem;
Source of impacts Compliant Non-compliant

Energy (J)

73.907586

82.15627099999998

Transfer (B)

49526

221836

Storage (B)

637549572

637549572

Case for a 2GB database:

ETSdiff percent comparison" style="padding: 1rem;
Source of impacts Compliant Non-compliant

Energy (J)

159.4871645

169.746055

Transfer (B)

50385

228225

Storage (B)

1178614788

1178614788

Case for a 4GB database:

ETSdiff percent comparison" style="padding: 1rem;
Source of impacts Compliant Non-compliant

Energy (J)

395.7629349999999

404.37447649999996

Transfer (B)

51597

238884

Storage (B)

2357214212

2357214212

Case for a 8GB database:

ETSdiff percent comparison" style="padding: 1rem;
Source of impacts Compliant Non-compliant

Energy (J)

992.128585

1005.4625534999999

Transfer (B)

52189

249499

Storage (B)

4685052932

4685052932