The use of Spring repository in a loop induces unnecessary calculations by the CPU and therefore superfluous energy consumption.
-
Noncompliant Code Example
-
- private final List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+The use of Spring repository in a loop induces unnecessary calculations by the CPU and therefore superfluous energy consumption.
- List<Employee> employees = new ArrayList<>();
-
- for (Integer id: ids) {
- Optional<Employee> employee = employeeRepository.findById(id); // Noncompliant
- if (employee.isPresent()) {
- employees.add(employee.get());
- }
- }
+## Noncompliant Code Example
-
SVG images generated by common drawing softwares contains unnecessary data: calc layer, metadata, namespaces and comments.
-
Noncompliant Code Example
-
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-<svg
+SVG images generated by common drawing softwares contains unnecessary data: calc layer, metadata, namespaces and comments.
+
+## Noncompliant Code Example
+
+```xml
+
+
+```
+
+## Compliant Solution
+
+```xml
+
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc b/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc
index 7e5fcc2a0..0e56f2845 100644
--- a/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc
@@ -1,31 +1,32 @@
-
If we are using too many conditional if-else statements it will impact performance since JVM will have to compare the conditions. We can think of using a switch statement instead of multiple if-else if possible. Switch statement has a performance advantage over if – else.
+If we are using too many conditional `if` – `else` statements it will impact performance since JVM will have to compare the conditions. We can think of using a switch statement instead of multiple `if` – `else` if possible. `switch` statement has a performance advantage over `if` – `else`.
-
Non-compliant Code Example
-
- int index = 1;
- int nb = 2;
+## Non-compliant Code Example
- if (nb > index) {
- nb = nb + index;
- } else {
- nb = nb - 1;
- }
- if (nb != index + 1) {
- nb = nb + index;
- } else {
- nb = nb - 1;
- }
+```java
+int index = 1;
+int nb = 2;
+if (nb > index) {
+ nb = nb + index;
+} else {
+ nb = nb - 1;
+}
+if (nb != index + 1) {
+ nb = nb + index;
+} else {
+ nb = nb - 1;
+}
+```
-
-
Compliant Code Example
-
- int index = 1;
- int nb = 2;
+## Compliant Code Example
- if (nb > index) {
- nb = nb + index;
- } else {
- nb = nb - 1;
- }
-
+```java
+int index = 1;
+int nb = 2;
+
+if (nb > index) {
+ nb = nb + index;
+} else {
+ nb = nb - 1;
+}
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc b/ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc
index 7f9e458fd..85d38acb6 100644
--- a/ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc
@@ -1,73 +1,78 @@
-
If possible, the utilisation of svg image format (or <svg/> html tag) is recommended over other image format.
-
Because SVGs are generally smaller than other image format, they’re less taxing on your server despite needing to render on load.
-
When to use SVG :
-
-
Your image is used for decorative website graphics, logos, icons, graphs and diagrams, and other simple images.
-
You image require animation.
-
You image need to be responsive and scale without lack of quality.
-
-
-
Some advantages of using SVG:
-
-
SVGs are scalable and will render pixel-perfect at any resolution whereas JPEGs, PNGs and GIFs will not.
-
SVGs are vector images and therefore are usually much smaller in file-size than bitmap-based images.
-
SVGs can be embedded into the HTML which means they can be cached, edited directly using CSS and indexed for greater accessibility.
-
SVGs can be animated directly or by using CSS or JavaScript making it easy for web designers to add interactivity to a site.
+If possible, the utilisation of svg image format (or `` html tag) is recommended over other image format.
+
+Because SVGs are generally smaller than other image format, they’re less taxing on your server despite needing to render on load.
+
+When to use SVG :
+
+- Your image is used for decorative website graphics, logos, icons, graphs and diagrams, and other simple images.
+- You image require animation.
+- You image need to be responsive and scale without lack of quality.
+
+Some advantages of using SVG:
+
+- SVGs are scalable and will render pixel-perfect at any resolution whereas JPEGs, PNGs and GIFs will not.
+- SVGs are vector images and therefore are usually much smaller in file-size than bitmap-based images.
+- SVGs can be embedded into the HTML which means they can be cached, edited directly using CSS and indexed for greater accessibility.
+- SVGs can be animated directly or by using CSS or JavaScript making it easy for web designers to add interactivity to a site.
+
+## Noncompliant Code Example
+
+```
+img_jpg = "image.jpg"
+```
+
+## Compliant Solution
+
+```
+img_svg = "image.svg"
+```
+
+## Noncompliant Code Example
+
+```
+public void foo() {
+ // ...
+ image_format = testImage("image.jpg")
+ // ...
+}
+```
+
+## Compliant Solution
+
+```
+public void foo() {
+ // ...
+ image_format = testImage("image.svg")
+ // ...
+}
+```
+
+## Noncompliant Code Example
+
+```
+public void foo() {
+ // ...
+ return ''
+ // ...
+}
+```
+
+## Compliant Solution
+
+```
+public void foo() {
+ // ...
+ return ''
+ // ...
+}
+```
+
+Or
+
+```
+ public void foo() {
+ // ...
+ return ('')
+ // ...
+}
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc b/ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc
index 0294f0a03..c42338993 100644
--- a/ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc
@@ -1,9 +1,13 @@
-
- Programs spend most of the time in loops. These can be resource consuming, especially when they integrate heavy processing (IO access). Moreover, the size of the data and processing inside the loops will not allow full use of hardware mechanisms such as the cache or compiler optimization mechanisms.
- For example, an array copy is potentially a non-performance source if it is poorly designed. Indeed, the use of a single copy loop can be twice as consuming as dedicated methods.
- Loops must be optimized to reduce processing time and make full use of hardware and processor mechanisms and optimizations.
- In the case of table copying (table), the native System.arraycopy.
- We can also use copyOf or clone that are slightly less efficient.
- The looping method will be outlawed.
-
-
Noncompliant Code Example
-
- int len = array.length;
- boolean[] copy = new boolean[array.length];
- for (int i = 0; i < len; i++) {
- copy[i] = array[i]; // Noncompliant
- }
- return copy;
-
+Using `System.arraycopy` to copy arrays
+
+Programs spend most of the time in loops. These can be resource consuming, especially when they integrate heavy processing (IO access). Moreover, the size of the data and processing inside the loops will not allow full use of hardware mechanisms such as the cache or compiler optimization mechanisms.
+
+For example, an array copy is potentially a non-performance source if it is poorly designed. Indeed, the use of a single copy loop can be twice as consuming as dedicated methods.
+Loops must be optimized to reduce processing time and make full use of hardware and processor mechanisms and optimizations.
+In the case of table copying (table), use the native `System.arraycopy`.
+We can also use `copyOf` or `clone` that are slightly less efficient.
+The looping method will be outlawed.
+
+## Noncompliant Code Example
+
+```java
+int len = array.length;
+boolean[] copy = new boolean[array.length];
+for (int i = 0; i < len; i++) {
+ copy[i] = array[i]; // Noncompliant
+}
+return copy;
+```
+
+## Compliant Solution
+
+```java
+int[] copy = new int[array.length];
+System.arraycopy(array, 0, copy, 0, array.length);
+return copy;
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc b/ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc
index d37bcef22..841ee9f8c 100644
--- a/ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc
@@ -1,29 +1,30 @@
-
- public void readPreferences(String filename)
- throws IllegalArgumentException,
- FileNotFoundException, IOException {
- if (filename == null) {
- throw new IllegalArgumentException ("filename is null");
- } //if
- //...
- InputStream in = new FileInputStream(filename);
- //...
- }
-
+## Noncompliant Code Example
+
+```java
+public void readPreferences(String filename) {
+ //...
+ InputStream in = null;
+ try {
+ in = new FileInputStream(filename);
+ } catch (FileNotFoundException e) {
+ logger.log(e);
+ }
+ in.read(...);
+ //...
+}
+```
+
+## Compliant Solution
+
+```java
+public void readPreferences(String filename) throws IllegalArgumentException, FileNotFoundException, IOException {
+ if (filename == null) {
+ throw new IllegalArgumentException ("filename is null");
+ }
+ //...
+ InputStream in = new FileInputStream(filename);
+ //...
+}
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc b/ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc
index b347d7141..49fcb223e 100644
--- a/ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc
@@ -1,19 +1,22 @@
-
When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. The example provided below illustrates what should be avoided.
-
Noncompliant Code Example
-
- List<String> objList = getData();
+When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. The example provided below illustrates what should be avoided.
- for (int i = 0; i < objList.size(); i++) { // Noncompliant
- // execute code
- }
+## Noncompliant Code Example
-
-
Compliant Solution
-
- List<String> objList = getData();
+```java
+List objList = getData();
- int size = objList.size();
- for (int i = 0; i < size; i++) {
- // execute code
- }
-
When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power.
-
NB : note that we are using the count() method to get the size of an array but it would work the same with the sizeof() and iterator_count() methods
-
-
Noncompliant Code Examples
-
- $array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
-
- // FOR STATEMENTS / Right operand
- for ($i = 0; $i < count($array); ++$i) {
- var_dump($array[$i]);
- }
-
- // FOR STATEMENTS / Left operand
- for ($i = 0; count($array) > $i; ++$i) {
- var_dump($array[$i]);
- }
-
- // WHILE STATEMENTS / Right operand
- $i = 0;
- while($i < count($array)) {
- var_dump($array[$i]);
- ++$i;
- }
-
- // WHILE STATEMENTS / Left operand
- $i = 0;
- while(count($array) > $i) {
- var_dump($array[$i]);
- ++$i;
- }
-
- // DO WHILE STATEMENTS / Right operand
- $i = 0;
- do {
- var_dump($array[$i]);
- ++$i;
- } while ($i < count($array));
-
- // DO WHILE STATEMENTS / Left operand
- $i = 0;
- do {
- var_dump($array[$i]);
- ++$i;
- } while (count($array) > $i);
-
-
-
Compliant Solution
-
- $array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
- // FOR STATEMENTS / Right operand
- $size = sizeof($array);
- for ($i = 0; $i < $size; ++$i) {
- var_dump($array[$i]);
- }
-
- // FOR STATEMENTS / Left operand
- $size = sizeof($array);
- for ($i = 0; $size > $i; ++$i) {
- var_dump($array[$i]);
- }
-
- // WHILE STATEMENTS / Right operand
- $i = 0;
- $size = count($array);
- while($i < $size) {
- var_dump($array[$i]);
- ++$i;
- }
-
- // WHILE STATEMENTS / Left operand
- $i = 0;
- $size = count($array);
- while($size > $i) {
- var_dump($array[$i]);
- ++$i;
- }
-
- // DO WHILE STATEMENTS / Right operand
- $i = 0;
- $size = count($array);
- do {
- var_dump($array[$i]);
- ++$i;
- } while ($i < $size);
-
- // DO WHILE STATEMENTS / Left operand
- $i = 0;
- $size = count($array);
- do {
- var_dump($array[$i]);
- ++$i;
- } while ($size > $i);
-
+When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power.
+
+NB : note that we are using the `count()` method to get the size of an array but it would work the same with the `sizeof()` and `iterator_count()` methods.
+
+## Noncompliant Code Example
+
+```php
+$array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
+
+// FOR STATEMENTS / Right operand
+for ($i = 0; $i < count($array); ++$i) {
+ var_dump($array[$i]);
+}
+
+// FOR STATEMENTS / Left operand
+for ($i = 0; count($array) > $i; ++$i) {
+ var_dump($array[$i]);
+}
+
+// WHILE STATEMENTS / Right operand
+$i = 0;
+while($i < count($array)) {
+ var_dump($array[$i]);
+ ++$i;
+}
+
+// WHILE STATEMENTS / Left operand
+$i = 0;
+while(count($array) > $i) {
+ var_dump($array[$i]);
+ ++$i;
+}
+
+// DO WHILE STATEMENTS / Right operand
+$i = 0;
+do {
+ var_dump($array[$i]);
+ ++$i;
+} while ($i < count($array));
+
+// DO WHILE STATEMENTS / Left operand
+$i = 0;
+do {
+ var_dump($array[$i]);
+ ++$i;
+} while (count($array) > $i);
+```
+
+## Compliant Solution
+
+```php
+$array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
+// FOR STATEMENTS / Right operand
+$size = sizeof($array);
+for ($i = 0; $i < $size; ++$i) {
+ var_dump($array[$i]);
+}
+
+// FOR STATEMENTS / Left operand
+$size = sizeof($array);
+for ($i = 0; $size > $i; ++$i) {
+ var_dump($array[$i]);
+}
+
+// WHILE STATEMENTS / Right operand
+$i = 0;
+$size = count($array);
+while($i < $size) {
+ var_dump($array[$i]);
+ ++$i;
+}
+
+// WHILE STATEMENTS / Left operand
+$i = 0;
+$size = count($array);
+while($size > $i) {
+ var_dump($array[$i]);
+ ++$i;
+}
+
+// DO WHILE STATEMENTS / Right operand
+$i = 0;
+$size = count($array);
+do {
+ var_dump($array[$i]);
+ ++$i;
+} while ($i < $size);
+
+// DO WHILE STATEMENTS / Left operand
+$i = 0;
+$size = count($array);
+do {
+ var_dump($array[$i]);
+ ++$i;
+} while ($size > $i);
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc b/ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc
index 253090269..00c2ac907 100644
--- a/ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc
@@ -1,19 +1,21 @@
-
- If you know in advance how many characters would be appended, initialize builder/buffer with the appropriate size.
- They will thus never have to be resized.
- This saves CPU cycles and therefore consumes less energy.
-
-
Noncompliant Code Example
-
- StringBuilder sb = new StringBuilder(); // Noncompliant
- for (int i = 0; i < 100; i++) {
- sb.append(...);
- }
-
-
Compliant Solution
-
- StringBuilder sb = new StringBuilder(100);
- for (int i = 0; i < 100; i++) {
- sb.append(...);
- }
-
+If you know in advance how many characters would be appended, initialize builder/buffer with the appropriate size.
+They will thus never have to be resized.
+This saves CPU cycles and therefore consumes less energy.
+
+## Noncompliant Code Example
+
+```java
+StringBuilder sb = new StringBuilder(); // Noncompliant
+for (int i = 0; i < 100; i++) {
+ sb.append(...);
+}
+```
+
+## Compliant Solution
+
+```java
+StringBuilder sb = new StringBuilder(100);
+for (int i = 0; i < 100; i++) {
+ sb.append(...);
+}
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC34/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC34/php/1GB.etsdiff.csv
new file mode 100644
index 000000000..5b56c3789
--- /dev/null
+++ b/ecocode-rules-specifications/src/main/rules/EC34/php/1GB.etsdiff.csv
@@ -0,0 +1,3 @@
+Energy (J),515.855638,516.9188409999999
+Transfer (B),1579453,1579457
+Storage (B),637549804,637549804
diff --git a/ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc b/ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc
index 5b8bd83c2..f7b2ab71d 100644
--- a/ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc
@@ -1,7 +1,10 @@
-
Inside complex code parts (for exemple multiple loops, complex data constructions...), avoid using try...catch...finally.
-
When an exception is thrown, a variable (the exception itself) is created in a catch block and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.
-
Noncompliant Code Example
-
+Inside complex code parts (for exemple multiple loops, complex data constructions...), avoid using try...catch...finally.
+
+When an exception is thrown, a variable (the exception itself) is created in a catch block and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.
+
+## Noncompliant Code Example
+
+```php
try
{
$picture = PDF_open_image_file($PDF, "jpeg", $imgFile, "", 0); // This is the original statement, this works on PHP4
@@ -11,10 +14,11 @@ catch(Exception $ex)
$msg = "Error opening $imgFile for Product $row['Identifier']";
throw new Exception($msg);
}
+```
-
The three sources of impacts of a code identified are:
-- Energy (measured in joules)
- - Transfer (measured in Bytes)
- - Storage (measured in Bytes)
- 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:
-
-
Total:
-
-
-
-
-
-
-
Compliant
-
-
-
-
-
Non-compliant
-
-
-
-
-
-
-
Energy
-
-
-
-
-
515.855638
-
-
-
-
-
516.9188409999999
-
-
-
-
-
-
-
Transfer
-
-
-
-
-
1579453
-
-
-
-
-
1579457
-
-
-
-
-
-
-
Storage
-
-
-
-
-
637549804
-
-
-
-
-
637549804
-
-
-
-
-
+```
+
+include::../../etsdiff-methodology.asciidoc[]
+
+## Case for a 1GB database:
+
+image::https://live.staticflickr.com/65535/52622382871_f19da08db4_o.png[ETSdiff percent comparison]
+
+[format=csv,cols="1h,1,1"]
+|===
+Source of impacts,Compliant,Non-compliant
+
+include::1GB.etsdiff.csv[]
+|===
diff --git a/ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc b/ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc
index d90cacc9e..14b3c3c5b 100644
--- a/ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc
@@ -1,8 +1,10 @@
-
Inside complex code parts (for example multiple loops, complex data constructions...), avoid using try...catch...finally.
-
When an exception is thrown, a variable (the exception itself) is created in a catch block, and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.
-
-
Noncompliant Code Example
-
+Inside complex code parts (for example multiple loops, complex data constructions...), avoid using try...catch...finally.
+
+When an exception is thrown, a variable (the exception itself) is created in a catch block, and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.
+
+## Noncompliant Code Example
+
+```python
try:
f = open(path)
print(fh.read())
@@ -10,12 +12,14 @@ except:
print('No such file '+path
finally:
f.close()
+```
-
When calling a global variable, the interpretation engine must check that it exists in all the scopes, that it has a value, etc. Passing global variables as arguments gives them the status of local variables inside the function, thus saving computing time (CPU cycles).
-
-
-CASE 1 (Avoid as possible):
-You are back on the service code. You see that the func1() uses globalVariabl1. Okay, but whats its value by now ? How does it change ? Who mutates the globalVariabl1 before it comes to this function ? What have been the sequence of all these mutations ? You would have no idea. It will be quite difficult to figure all this out.
-
-CASE 2 (Recommended):
-You are back to you code, and see that the func0() fetches something and then passes it to func1(param1) as a parameter. You clearly know what the data is, how does it gets here.
-
-
Noncompliant Code Example
-
- var aGlobal = new String('Hello');
-
- function globalLength(){
- length = aGlobal.length;
- console.log(length);
- }
-
- globalLength();
-
-
Compliant Solution
-
- var aGlobal = new String('Hello');
-
- function someVarLength(str){
- length = str.length;
- console.log(length);
- }
-
- somVarLength(aGlobal);
-
\ No newline at end of file
+Prefer local variables as parameters
+
+When calling a global variable, the interpretation engine must check that it exists in all the scopes, that it has a value, etc. Passing global variables as arguments gives them the status of local variables inside the function, thus saving computing time (CPU cycles).
+
+## CASE 1 (Avoid as possible)
+
+You are back on the service code. You see that the `func1()` uses `globalVariabl1`. Okay, but whats its value by now ? How does it change ? Who mutates the `globalVariabl1` before it comes to this function ? What have been the sequence of all these mutations ? You would have no idea. It will be quite difficult to figure all this out.
+
+## CASE 2 (Recommended)
+
+You are back to you code, and see that the `func0()` fetches something and then passes it to `func1(param1)` as a parameter. You clearly know what the data is, how does it gets here.
+
+## Noncompliant Code Example
+
+```java
+var aGlobal = new String('Hello');
+
+function globalLength(){
+ length = aGlobal.length;
+ console.log(length);
+}
+
+globalLength();
+```
+
+## Compliant Solution
+
+```java
+var aGlobal = new String('Hello');
+
+function someVarLength(str){
+ length = str.length;
+ console.log(length);
+}
+
+somVarLength(aGlobal);
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc b/ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc
index 6e9687fa7..94021a9e6 100644
--- a/ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc
@@ -1,27 +1,29 @@
-
- Prefer local variables as parameters
-
-
When calling a global variable, the interpretation engine must check that it exists in all the scopes, that it has a value, etc. Passing global variables as arguments gives them the status of local variables inside the function, thus saving computing time (CPU cycles).
-
-
Noncompliant Code Example
-
- var aGlobal = new String('Hello');
-
- function globalLength(){
+Prefer local variables as parameters
+
+When calling a global variable, the interpretation engine must check that it exists in all the scopes, that it has a value, etc. Passing global variables as arguments gives them the status of local variables inside the function, thus saving computing time (CPU cycles).
+
+## Noncompliant Code Example
+
+```php
+var aGlobal = new String('Hello');
+
+function globalLength(){
length = aGlobal.length;
console.log(length);
- }
+}
+
+globalLength();
+```
+
+## Compliant Solution
- globalLength();
-
-
Compliant Solution
-
- var aGlobal = new String('Hello');
+```php
+var aGlobal = new String('Hello');
- function someVarLength(str){
+function someVarLength(str){
length = str.length;
console.log(length);
- }
+}
- somVarLength(aGlobal);
-
\ No newline at end of file
+somVarLength(aGlobal);
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc b/ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc
index c92e7e5be..b777840a9 100644
--- a/ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc
@@ -1,20 +1,24 @@
-
When function calls global variables, a lot a CPU cycles is consumed.
-
Noncompliant Code Example
-
+When function calls global variables, a lot a CPU cycles is consumed.
+
+## Noncompliant Code Example
+
+```python
global_var = 'foo'
def print_global_var_details():
print(len(global_var)) # Noncompliant
print('Global var : ', global_var) # Noncompliant
print('Global var : ' + global_var) # Noncompliant
print_global_var_details()
-
Use generator comprehension instead of list comprehension in for loop declaration.
-
Python generators resemble lazy lists from other programming languages: when iterated over, they compute their values on the fly. They lack some list behaviors (indexing, len method, ...) but are memory-efficient, as they do not store each of their values in memory, unlike lists. Thus, when declared in a for-loop declaration, list comprehensions can be safely replaced with generator comprehensions.
-
For more details on list comprehensions vs generator comprehensions, see Python documentation.
-
Noncompliant Code Example
-
+Use generator comprehension instead of list comprehension in for loop declaration.
+
+Python generators resemble lazy lists from other programming languages: when iterated over, they compute their values on the fly. They lack some list behaviors (indexing, len method, ...) but are memory-efficient, as they do not store each of their values in memory, unlike lists. Thus, when declared in a for-loop declaration, list comprehensions can be safely replaced with generator comprehensions.
+
+For more details on list comprehensions vs generator comprehensions, see https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions[Python documentation].
+
+## Noncompliant Code Example
+
+```python
for var in [var2 for var2 in range(100)]:
...
-
-
Compliant Solution
-
+
+```
+
+## Compliant Solution
+
+```python
for var in (var2 for var2 in range(100)):
...
-
Use PreparedStatement instead of Statement, because SQL will only commit the query once, whereas if you used only one statement, it would commit the query every time and thus induce unnecessary calculations by the CPU and therefore superfluous energy consumption.
- public void select() {
- PreparedStatement statement = connection.prepareStatement(INSERT INTO persons(id, name) VALUES(?, ?));
+Use `PreparedStatement` instead of `Statement`, because SQL will only commit the query once, whereas if you used only one statement, it would commit the query every time and thus induce unnecessary calculations by the CPU and therefore superfluous energy consumption.
- statement.setInt(1, 2);
- statement.setString(2, "Toto");
- statement.executeQuery();
- }
-
Using List instead of Arrays with Foreach save CPU cycles calculations and RAM consumption.
-
Noncompliant Code Example
-
- private final Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+Using List instead of Arrays with Foreach save CPU cycles calculations and RAM consumption.
- for (Integer i : intArray) {
- ...
- }
+## Noncompliant Code Example
-
Do not unnecessarily assign values to variables. It increases the use of RAM memory.
-
Noncompliant Code Example
-
+Do not unnecessarily assign values to variables. It increases the use of RAM memory.
+
+## Noncompliant Code Example
+
+```java
String var1 = getValue();
return var1;
String var2 = "hello"
-var2 = "world" //Non compliant cause never assigned
+var2 = "world" //Non compliant cause never assigned
+```
+
+## Compliant Solution
-
PHP allows declaring a string with simple or double quotes. Using double quotes allows developers to insert variables which will be substituted during execution. When the string has no variables, using single quotes prevents PHP from searching for non-existent variables. It will save CPU cycles consumption and RAM usage.
-
Noncompliant Code Example
-
+PHP allows declaring a string with simple or double quotes. Using double quotes allows developers to insert variables which will be substituted during execution. When the string has no variables, using single quotes prevents PHP from searching for non-existent variables. It will save CPU cycles consumption and RAM usage.
+
+## Noncompliant Code Example
+
+```php
myFunction("name", "age", "IsStudent");
- $lastName = "Hugo";
- $concatenatedString = "$lastName is a student";
-
The three sources of impacts of a code identified are:
-- Energy (measured in joules)
- - Transfer (measured in Bytes)
- - Storage (measured in Bytes)
- 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:
-
-
Total:
-
-
-
-
-
-
-
Compliant
-
-
-
-
-
Non-compliant
-
-
-
-
-
-
-
Energy
-
-
-
-
-
3.041966
-
-
-
-
-
1.2651545000000002
-
-
-
-
-
-
-
Transfer
-
-
-
-
-
68520884
-
-
-
-
-
68588123
-
-
-
-
-
-
-
Storage
-
-
-
-
-
637548795
-
-
-
-
-
637548795
-
-
-
-
-
+```
+
+include::../../etsdiff-methodology.asciidoc[]
+
+## Case for a 1GB database:
+
+image::https://live.staticflickr.com/65535/52621866212_de15608a41_o.png[ETSdiff percent comparison]
+
+[format=csv,cols="1h,1,1"]
+|===
+Source of impacts,Compliant,Non-compliant
+
+include::1GB.etsdiff.csv[]
+|===
diff --git a/ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc b/ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc
index 0a94f3529..09e0eda41 100644
--- a/ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc
@@ -1,27 +1,31 @@
-
- The shape using the quotation marks (") allows the developer to insert variables that will be substituted at run time.
- But if the string does not have a variable, use quotes (') instead.
- Thus, language will not look for variables to substitute, which will reduce the consumption of CPU cycles.
-
-
Noncompliant Code Example
-
- # in variables
- firstname = "Andrea" # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}}
-
- # in functions
- def my_function(name, age):
- print(name + 'is' + age + ' yo.')
-
- my_function("Robert", 12) # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}}
-
+The shape using the quotation marks (") allows the developer to insert variables that will be substituted at run time.
+
+But if the string does not have a variable, use quotes (') instead.
+
+Thus, language will not look for variables to substitute, which will reduce the consumption of CPU cycles.
+
+## Noncompliant Code Example
+
+```python
+# in variables
+firstname = "Andrea" # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}}
+
+# in functions
+def my_function(name, age):
+ print(name + 'is' + age + ' yo.')
+
+my_function("Robert", 12) # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}}
+```
+
+## Compliant Solution
+
+```python
+# in variables
+firstname = 'Andrea'
+
+# in functions
+def my_function(name, age):
+ print(name + 'is' + age + ' yo.')
+
+my_function('Robert', 12)
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc b/ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc
index 3c55323e5..a0c7b961a 100644
--- a/ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc
@@ -1,7 +1,13 @@
-
The form $i++ creates a temporary variable whereas ++$i does not. It save CPU cycles.
-
Noncompliant Code Example
-
+The form `$i++` creates a temporary variable whereas `++$i` does not. It save CPU cycles.
+
+## Noncompliant Code Example
+
+```java
i++ // Noncompliant
-
The form $i++ creates a temporary variable whereas ++$i does not. It save CPU cycles.
-
Noncompliant Code Example
-
+The form `$i++` creates a temporary variable whereas `++$i` does not. It save CPU cycles.
+
+## Noncompliant Code Example
+
+```php
$i++
-
-
Compliant Solution
-
++$i
-
The three sources of impacts of a code identified are:
-- Energy (measured in joules)
- - Transfer (measured in Bytes)
- - Storage (measured in Bytes)
- 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:
-
-
Total:
-
-
-
-
-
-
-
Compliant
-
-
-
-
-
Non-compliant
-
-
-
-
-
-
-
Energy
-
-
-
-
-
1.8163645000000002
-
-
-
-
-
0.2613885000000001
-
-
-
-
-
-
-
Transfer
-
-
-
-
-
11265758
-
-
-
-
-
11290494
-
-
-
-
-
-
-
Storage
-
-
-
-
-
637548673
-
-
-
-
-
637548673
-
-
-
-
-
\ No newline at end of file
+```
+
+## Compliant Solution
+
+```php
+++$i
+```
+
+include::../../etsdiff-methodology.asciidoc[]
+
+## Case for a 1GB database:
+
+image::https://live.staticflickr.com/65535/52622379586_f84c767111_o.png[ETSdiff percent comparison]
+
+[format=csv,cols="1h,1,1"]
+|===
+Source of impacts,Compliant,Non-compliant
+
+include::1GB.etsdiff.csv[]
+|===
diff --git a/ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc b/ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc
index 5d8c46aa1..e32cd94db 100644
--- a/ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc
@@ -1,23 +1,24 @@
-
Do not call a function when declaring a for-type loop in order to avoid function calls each iterations. It saves CPU cycles.
-
Noncompliant Code Example
-
- public void foo() {
- for (int i = 0; i < getMyValue(); i++) { // Noncompliant
- System.out.println(i);
- boolean b = getMyValue() > 6;
- }
- }
+Do not call a function when declaring a for-type loop in order to avoid function calls each iterations. It saves CPU cycles.
-
-
Compliant Solution
-
+## Noncompliant Code Example
- public void foo() {
- int myValue = getMyValue();
- for (int i = 0; i < myValue; i++) {
- System.out.println(i);
- boolean b = getMyValue() > 6;
- }
+```java
+public void foo() {
+ for (int i = 0; i < getMyValue(); i++) { // Noncompliant
+ System.out.println(i);
+ boolean b = getMyValue() > 6;
}
+}
+```
+
+## Compliant Solution
-
+```java
+public void foo() {
+ int myValue = getMyValue();
+ for (int i = 0; i < myValue; i++) {
+ System.out.println(i);
+ boolean b = getMyValue() > 6;
+ }
+}
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC69/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC69/php/1GB.etsdiff.csv
new file mode 100644
index 000000000..227f4def5
--- /dev/null
+++ b/ecocode-rules-specifications/src/main/rules/EC69/php/1GB.etsdiff.csv
@@ -0,0 +1,3 @@
+Energy (J),144.635057,144.58341249999998
+Transfer (B),50000,50004
+Storage (B),637549590,637549590
diff --git a/ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc b/ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc
index c71d96a37..0da3cde83 100644
--- a/ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc
@@ -1,12 +1,16 @@
-
Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.
-
Noncompliant Code Example
-
+Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.
+
+## Noncompliant Code Example
+
+```php
for ($i = 0; $i <= foo(); $i++) { // Noncompliant
// ......
}
-
+}
+```
+
+include::../../etsdiff-methodology.asciidoc[]
+
+## Case for a 1GB database:
-
The three sources of impacts of a code identified are:
-- Energy (measured in joules)
- - Transfer (measured in Bytes)
- - Storage (measured in Bytes)
- 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.
-
+image::https://live.staticflickr.com/65535/52622634654_bf3c3d9ba8_o.png[ETSdiff percent comparison]
-
Case for a 1GB database:
-
+[format=csv,cols="1h,1,1"]
+|===
+Source of impacts,Compliant,Non-compliant
-
Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.
-
Noncompliant Code Example
-
+Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.
+
+## Noncompliant Code Example
+
+```python
for i in my_function(): # Noncompliant
......
+```
-
-
Compliant Solution
-
+## Compliant Solution
+
+```python
limit = my_function()
for i in limit:
......
-
Executing SQL queries in loop induced unnecessary calculation by the cpu, RAM usage and network transfer.
-
Noncompliant Code Example
-
- public void foo() {
- ...
- String baseQuery = "SELECT name FROM users where id = ";
-
- for (int i = 0; i < 20; i++) {
-
- String query = baseQuery.concat("" + i);
- Statement st = conn.createStatement();
- ResultSet rs = st.executeQuery(query); // Noncompliant
-
- // iterate through the java resultset
- while (rs.next()) {
- String name = rs.getString("name");
- System.out.println(name);
- }
- st.close();
- }
- ...
- }
+Executing SQL queries in loop induced unnecessary calculation by the CPU, RAM usage and network transfer.
-
-
Compliant Solution
-
+## Noncompliant Code Example
- public void foo() {
- ...
- String query = "SELECT name FROM users where id in (0 ";
- for (int i = 1; i < 20; i++) {
+```java
+public void foo() {
+ // ...
+ String baseQuery = "SELECT name FROM users where id = ";
- query = baseQuery.concat("," + i);
- }
+ for (int i = 0; i < 20; i++) {
- query = baseQuery.concat(")");
+ String query = baseQuery.concat("" + i);
Statement st = conn.createStatement();
- ResultSet rs = st.executeQuery(query); // compliant
+ ResultSet rs = st.executeQuery(query); // Noncompliant
// iterate through the java resultset
while (rs.next()) {
@@ -43,7 +19,32 @@
System.out.println(name);
}
st.close();
- ...
- }
+ }
+ // ...
+}
+```
+
+## Compliant Solution
-
+```java
+public void foo() {
+ // ...
+ String query = "SELECT name FROM users where id in (0 ";
+ for (int i = 1; i < 20; i++) {
+
+ query = baseQuery.concat("," + i);
+ }
+
+ query = baseQuery.concat(")");
+ Statement st = conn.createStatement();
+ ResultSet rs = st.executeQuery(query); // compliant
+
+ // iterate through the java resultset
+ while (rs.next()) {
+ String name = rs.getString("name");
+ System.out.println(name);
+ }
+ st.close();
+ // ...
+}
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC72/php/1GB.etsdiff.csv
new file mode 100644
index 000000000..b006091ac
--- /dev/null
+++ b/ecocode-rules-specifications/src/main/rules/EC72/php/1GB.etsdiff.csv
@@ -0,0 +1,3 @@
+Energy (J),73.907586,82.15627099999998
+Transfer (B),49526,221836
+Storage (B),637549572,637549572
diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/2GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC72/php/2GB.etsdiff.csv
new file mode 100644
index 000000000..73f5bac22
--- /dev/null
+++ b/ecocode-rules-specifications/src/main/rules/EC72/php/2GB.etsdiff.csv
@@ -0,0 +1,3 @@
+Energy (J),159.4871645,169.746055
+Transfer (B),50385,228225
+Storage (B),1178614788,1178614788
diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/4GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC72/php/4GB.etsdiff.csv
new file mode 100644
index 000000000..4c253ef72
--- /dev/null
+++ b/ecocode-rules-specifications/src/main/rules/EC72/php/4GB.etsdiff.csv
@@ -0,0 +1,3 @@
+Energy (J),395.7629349999999,404.37447649999996
+Transfer (B),51597,238884
+Storage (B),2357214212,2357214212
diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/8GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC72/php/8GB.etsdiff.csv
new file mode 100644
index 000000000..2a518e5eb
--- /dev/null
+++ b/ecocode-rules-specifications/src/main/rules/EC72/php/8GB.etsdiff.csv
@@ -0,0 +1,3 @@
+Energy (J),992.128585,1005.4625534999999
+Transfer (B),52189,249499
+Storage (B),4685052932,4685052932
diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc b/ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc
index 7973ec509..12fe0d7b7 100644
--- a/ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc
@@ -1,349 +1,91 @@
-
Executing SQL queries in loop induced unnecessary network transfert, calculation by the cpu and RAM usage.
-
Noncompliant Code Example
-
- public function foo() {
- ...
- $baseQuery = "SELECT name FROM users where id = ";
+Executing SQL queries in loop induced unnecessary network transfert, calculation by the cpu and RAM usage.
+
+## Noncompliant Code Example
+
+```php
+public function foo() {
+ ...
+ $baseQuery = "SELECT name FROM users where id = ";
- for ($i = 0; $i < 20; ++$i) {
+ 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
+ $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);
- }
+ // iterate through the result
...
+ mysql_close($connection);
}
+ ...
+}
+```
-
-
Compliant Solution
-
+## Compliant Solution
- public function foo() {
- ...
- $query = "SELECT name FROM users where id in (";
+```php
+public function foo() {
+ ...
+ $query = "SELECT name FROM users where id in (";
- for ($i = 0; $i < 20; ++$i) {
- $query .= ',' . $i;
- }
- $query .= ')';
+ 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
+ $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);
- }
+ // iterate through the result
+ ...
+ mysql_close($connection);
+}
+```
+
+include::../../etsdiff-methodology.asciidoc[]
+
+## Case for a 1GB database:
+
+image::https://live.staticflickr.com/65535/52622813465_9c453a43b1_w.jpg[ETSdiff percent comparison" style="padding: 1rem;]
+
+[format=csv,cols="1h,1,1"]
+|===
+Source of impacts,Compliant,Non-compliant
+
+include::1GB.etsdiff.csv[]
+|===
+
+## Case for a 2GB database:
+
+image::https://live.staticflickr.com/65535/52622862388_720fd219ba_o.png[ETSdiff percent comparison" style="padding: 1rem;]
+
+[format=csv,cols="1h,1,1"]
+|===
+Source of impacts,Compliant,Non-compliant
+
+include::2GB.etsdiff.csv[]
+|===
+
+## Case for a 4GB database:
+
+image::https://live.staticflickr.com/65535/52622814395_f8aab7a5c0_o.png[ETSdiff percent comparison" style="padding: 1rem;]
-
+[format=csv,cols="1h,1,1"]
+|===
+Source of impacts,Compliant,Non-compliant
-
The three sources of impacts of a code identified are:
- - Energy (measured in joules)
- - Transfer (measured in Bytes)
- - Storage (measured in Bytes)
- 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.
-
+include::4GB.etsdiff.csv[]
+|===
-
+[format=csv,cols="1h,1,1"]
+|===
+Source of impacts,Compliant,Non-compliant
-
Case for a 8GB database:
-
-
Total:
-
-
-
-
-
-
-
Compliant
-
-
-
-
-
Non-compliant
-
-
-
-
-
-
-
Energy
-
-
-
-
-
992.128585
-
-
-
-
-
1005.4625534999999
-
-
-
-
-
-
-
Transfer
-
-
-
-
-
52189
-
-
-
-
-
249499
-
-
-
-
-
-
-
Storage
-
-
-
-
-
4685052932
-
-
-
-
-
4685052932
-
-
-
-
-
\ No newline at end of file
+include::8GB.etsdiff.csv[]
+|===
diff --git a/ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc b/ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc
index 2323c02f5..ae85dfe3e 100644
--- a/ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc
@@ -1,21 +1,23 @@
-
Executing SQL queries in loop induced unnecessary calculation by the cpu, RAM usage and network transfer.
-
Noncompliant Code Example
-
- def foo():
- ...
- results = []
- for id in range(20):
- results.append(cursor.execute("SELECT name FROM users where id = ?", (id)).fetchone()) # Noncompliant {{Avoid performing SQL queries within a loop}}
- ...
-
-
Compliant Solution
-
+Executing SQL queries in loop induced unnecessary calculation by the CPU, RAM usage and network transfer.
- def foo():
- ...
- ids = range(20)
- results = cursor.execute("SELECT name FROM users where id IN ({0})".format(', '.join("?" * len(ids))), ids).fetchmany() # Compliant
- ...
- }
+## Noncompliant Code Example
-
+```python
+def foo():
+ ...
+ results = []
+ for id in range(20):
+ results.append(cursor.execute("SELECT name FROM users where id = ?", (id)).fetchone()) # Noncompliant {{Avoid performing SQL queries within a loop}}
+ ...
+```
+
+## Compliant Solution
+
+```python
+def foo():
+ ...
+ ids = range(20)
+ results = cursor.execute("SELECT name FROM users where id IN ({0})".format(', '.join("?" * len(ids))), ids).fetchmany() # Compliant
+ ...
+}
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc b/ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc
index 35ffbf7af..4f1299b18 100644
--- a/ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc
@@ -1,21 +1,21 @@
-
Database servers have to resolve schema fields when using asterisk symbol (*). Knowing and using the schema saves CPU cycles and network transfer.
-
Noncompliant Code Example
-
- public void foo() {
- ...
- String baseQuery = "SELECT * FROM users"; // Noncompliant
+Database servers have to resolve schema fields when using asterisk symbol (`*`). Knowing and using the schema saves CPU cycles and network transfer.
- ...
- }
+## Noncompliant Code Example
-
Database servers have to resolve schema fields when using asterisk symbol (*). Knowing and using the schema saves CPU cycles and network transfer.
-
Noncompliant Code Example
-
- public function foo() {
- ...
- $baseQuery = "SELECT * FROM users"; // Noncompliant
+Database servers have to resolve schema fields when using asterisk symbol (`*`). Knowing and using the schema saves CPU cycles and network transfer.
- ...
- }
-
-
Compliant Solution
-
- public function foo() {
- ...
- $baseQuery = "SELECT id,name, address FROM users ";
- ...
- }
-
-
The three sources of impacts of a code identified are:
-- Energy (measured in joules)
- - Transfer (measured in Bytes)
- - Storage (measured in Bytes)
- 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.
-
+## Noncompliant Code Example
-
+## Compliant Solution
+
+```php
+public function foo() {
+ ...
+ $baseQuery = "SELECT id,name, address FROM users ";
+ ...
+}
+```
+
+include::../../etsdiff-methodology.asciidoc[]
+
+## Case for a 1GB database:
+
+image::https://live.staticflickr.com/65535/52622636584_52938fcf7e_o.png[ETSdiff percent comparison]
+
+[format=csv,cols="1h,1,1"]
+|===
+Source of impacts,Compliant,Non-compliant
+
+include::1GB.etsdiff.csv[]
+|===
diff --git a/ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc b/ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc
index 35ffbf7af..3b9b41c0f 100644
--- a/ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc
@@ -1,21 +1,21 @@
-
Database servers have to resolve schema fields when using asterisk symbol (*). Knowing and using the schema saves CPU cycles and network transfer.
-
Noncompliant Code Example
-
- public void foo() {
- ...
- String baseQuery = "SELECT * FROM users"; // Noncompliant
+Database servers have to resolve schema fields when using asterisk symbol (`*`). Knowing and using the schema saves CPU cycles and network transfer.
- ...
- }
+## Noncompliant Code Example
-
- Don't concatenate Strings in loop. User StringBuilder instead.
- Strings are immutable so each time you concatenate a String, a new String is created. This is a waste of memory and CPU.
-
+Don't concatenate Strings in loop. Use `StringBuilder instead.
-
Noncompliant Code Example
-
+Strings are immutable so each time you concatenate a String, a new String is created. This is a waste of memory and CPU.
- public String concatenateStrings(String[] strings) {
- String result = "";
+## Noncompliant Code Example
- for (String string : strings) {
- result += string; // Noncompliant
- }
- return result;
+```java
+public String concatenateStrings(String[] strings) {
+ String result = "";
+
+ for (String string : strings) {
+ result += string; // Noncompliant
}
+ return result;
+}
- public String concatenateStrings2() {
- String result = "";
+public String concatenateStrings2() {
+ String result = "";
- for (int i = 0; i < 1000; ++i) {
- result += "another"; // Noncompliant
- }
- return result;
+ for (int i = 0; i < 1000; ++i) {
+ result += "another"; // Noncompliant
}
+ return result;
+}
+```
-
-
-
Compliant Solution
-
+## Compliant Solution
- public String concatenateStrings(String[] strings) {
- StringBuilder result = new StringBuilder();
+```java
+public String concatenateStrings(String[] strings) {
+ StringBuilder result = new StringBuilder();
- for (String string : strings) {
- result.append(string);
- }
- return result.toString();
+ for (String string : strings) {
+ result.append(string);
}
-
-
- Avoid usage of static collections.
- If you want to use static collections make them final and create for example a singleton if needed containing the collections.
- The static fields are more complicated for the Garbage Collector to manage and can lead to memory leaks.
-
-
-
Noncompliant Code Example
-
-
- /**
- * Not compliant
- */
- public class AvoidUsageOfStaticCollections {
- public static final List<> LIST = new ArrayList<>();
- public static final Set<> SET = new HashSet<>();
- public static final Map<> MAP = new HashMap<>();
- }
+Avoid usage of static collections.
-
+If you want to use static collections make them final and create for example a singleton if needed containing the collections.
-
Compliant Solution
-
+The static fields are more complicated for the Garbage Collector to manage and can lead to memory leaks.
- /**
- * Compliant
- */
- public class GoodUsageOfStaticCollections {
- public static volatile GoodUsageOfStaticCollections INSTANCE = new GoodUsageOfStaticCollections();
+## Noncompliant Code Example
- public final List<> LIST = new ArrayList<>();
- public final Set<> SET = new HashSet<>();
- public final Map<> MAP = new HashMap<>();
+```java
+/**
+ * Not compliant
+ */
+public class AvoidUsageOfStaticCollections {
+ public static final List<> LIST = new ArrayList<>();
+ public static final Set<> SET = new HashSet<>();
+ public static final Map<> MAP = new HashMap<>();
+}
+```
- private GoodUsageOfStaticCollections() {
- }
- }
+## Compliant Solution
+
+```java
+/**
+ * Compliant
+ */
+public class GoodUsageOfStaticCollections {
+ public static volatile GoodUsageOfStaticCollections INSTANCE = new GoodUsageOfStaticCollections();
-
\ No newline at end of file
+ public final List<> LIST = new ArrayList<>();
+ public final Set<> SET = new HashSet<>();
+ public final Map<> MAP = new HashMap<>();
+
+ private GoodUsageOfStaticCollections() {
+ }
+}
+```
diff --git a/ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc b/ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc
index f0aed4f4f..188b8f648 100644
--- a/ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc
+++ b/ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc
@@ -1,67 +1,53 @@
-
- Avoid using Pattern.compile() in a non-static context.
- This operation requires a significant amount of computational power, Using a single match saves CPU cycles and RAM consumption.
-
+Avoid using `Pattern.compile()` in a non-static context.
+This operation requires a significant amount of computational power, Using a single match saves CPU cycles and RAM consumption.
-
Noncompliant Code Example
-
-
- public class AvoidRegexPatternNotStatic {
-
- public boolean foo() {
- final Pattern pattern = Pattern.compile("foo"); // Noncompliant
- return pattern.matcher("foo").find();
- }
+## Noncompliant Code Example
+```java
+public class AvoidRegexPatternNotStatic {
+ public boolean foo() {
+ final Pattern pattern = Pattern.compile("foo"); // Noncompliant
+ return pattern.matcher("foo").find();
}
+}
+```
-
-
-
Compliant Solution N°1
-
-
- public class ValidRegexPattern {
+## Compliant Solution N°1
- private static final Pattern pattern = Pattern.compile("foo"); // Compliant
-
- public boolean foo() {
- return pattern.matcher("foo").find();
- }
+```java
+public class ValidRegexPattern {
+ private static final Pattern pattern = Pattern.compile("foo"); // Compliant
+ public boolean foo() {
+ return pattern.matcher("foo").find();
}
+}
+```
-
-
-
Compliant Solution N°2
-
-
- public class ValidRegexPattern2 {
+## Compliant Solution N°2
- private final Pattern pattern = Pattern.compile("foo"); // Compliant
-
- public boolean foo() {
- return pattern.matcher("foo").find();
- }
+```java
+public class ValidRegexPattern2 {
+ private final Pattern pattern = Pattern.compile("foo"); // Compliant
+ public boolean foo() {
+ return pattern.matcher("foo").find();
}
+}
+```
-
-
-
Compliant Solution N°3
-
-
- public class ValidRegexPattern3 {
+## Compliant Solution N°3
- private final Pattern pattern;
-
- public ValidRegexPattern3() {
- pattern = Pattern.compile("foo"); // Compliant
- }
-
- public boolean foo() {
- return pattern.matcher("foo").find();
- }
+```java
+public class ValidRegexPattern3 {
+ private final Pattern pattern;
+ public ValidRegexPattern3() {
+ pattern = Pattern.compile("foo"); // Compliant
}
-