Skip to content

Instantly share code, notes, and snippets.

@pbloem
Last active September 23, 2016 16:19
Show Gist options
  • Save pbloem/1523283211454ec58ce9c5b45204eebd to your computer and use it in GitHub Desktop.
Save pbloem/1523283211454ec58ce9c5b45204eebd to your computer and use it in GitHub Desktop.
Example of strange Java behavior
import static java.lang.System.currentTimeMillis;
import java.util.Arrays;
import java.util.Random;
public class Sandbox
{
public static final Random RANDOM = new Random();
public static double sumWith = 0;
public static double sumWithout = 0;
public static double t0 = 0;
public static void main(String[] args)
{
int size = 100;
for(int i = 0; i < 20000; i++)
{
int[] a = new int[size];
int[] b = new int[size];
for(int j = 0; j < size; j++)
{
a[j] = RANDOM.nextInt(size * 100);
b[j] = RANDOM.nextInt(size * 100);
Arrays.sort(a);
Arrays.sort(b);
}
t0 = System.nanoTime();
with(a, b);
sumWith += System.nanoTime() - t0;
t0 = System.nanoTime();
without(a, b);
sumWithout += System.nanoTime() - t0;
}
System.out.println("time with: " + sumWith + " ns.");
System.out.println("time without: " + sumWithout + " ns.");
}
public static int with(int[] a, int[] b)
{
int i = 0, j = 0;
int res = 0;
while(i < a.length && j < b.length)
{
if(a[i] > b[j])
j ++;
else if(a[i] < b[j])
i ++;
else if(a[i] == b[j]) // ?
{
res ++;
i ++;
j ++;
}
}
return res;
}
public static int without(int[] a, int[] b)
{
int i = 0, j = 0;
int res = 0;
while(i < a.length && j < b.length)
{
if(a[i] > b[j])
j ++;
else if(a[i] < b[j])
i ++;
else // if(a[i] == b[j])
{
res ++;
i ++;
j ++;
}
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment