C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
So: This loop always displays the initial value 10, but then it generates and tests random numbers.
Java program that uses do-while loop
import java.util.*;
public class Program {
public static void main(String[] args) {
// Used for the loop.
Random random = new Random();
// Use a special value in the first iteration of the loop.
int i = 10;
do {
System.out.println(i);
// On following iterations, use a random number.
// ... Behavior changes on the second and further iterations.
i = random.nextInt(20);
} while (i <= 10);
}
}
Output
10
6
8
0
So: We do not need to check the initial value. But all values after the initial one are checked.
Java program that uses do, prefix decrement
public class Program {
public static void main(String[] args) {
int i = 10;
do {
// We do not need to check the first iteration's range.
// ... Just use it directly with no checks.
System.out.println(i);
} while (--i >= 0);
}
}
Output
10
9
8
7
6
5
4
3
2
1
0
Version 1: We benchmark a do-while loop. This version reduces the number of expensive bounds checks.
Version 2: Here we use a while-loop, which performs a bounds check on the first iteration.
Result: When a bounds check is expensive, like expensiveBound(), it improves performance to reduce these checks.
Java program that benchmarks do-loop, expensive bounds
public class Program {
static int expensiveBound(int number) {
// Return 100 in an expensive way.
if ((number % 2) == 0) {
int a = Integer.parseInt("10");
int b = Integer.parseInt("90");
return a + b;
} else {
return 100;
}
}
public static void main(String[] args) {
System.out.println(expensiveBound(0));
long t1 = System.currentTimeMillis();
// Version 1: use do-loop with expensive bound check.
for (int i = 0; i < 100000; i++) {
int x = 0;
int count = 0;
do {
count++;
x++;
} while (x < expensiveBound(i));
// Check validity.
if (count != 100) {
System.out.println(count);
return;
}
}
long t2 = System.currentTimeMillis();
// Version 2: use for-loop with expensive bound check.
for (int i = 0; i < 100000; i++) {
int count = 0;
for (int x = 0; x < expensiveBound(i); x++) {
count++;
}
// Check validity.
if (count != 100) {
System.out.println(count);
return;
}
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
Output
100
99 ms, do-while with expensiveBounds()
107 ms, for with expensiveBounds()