I am playing around with different ways to read numbers from a file and how efficient they are, here is one method I am currently using:
public static long getNumbers1() {
final long startTime = System.nanoTime();
try
{
String input = new String(Files.readAllBytes(file.toPath()));
String[] stringNumbers = input.split("\\W");
int[] numbers = new int[stringNumbers.length];
for(int index = 1;index < stringNumbers.length;index++)
{
numbers[index] = Integer.parseInt(stringNumbers[index]);
}
}
catch (IOException e)
{
e.printStackTrace();
}
final long endTime = System.nanoTime();
System.out.println(endTime + " | " + startTime + " | " + (endTime - startTime));
return endTime - startTime;
}
file
is declared at a global scope:
private static File file = new File(System.getProperty("user.dir") + "/data/numtest.txt");
This method is then run by the following means:
for (int index = 0;index < 10;index++)
{
getNumbers1();
}
Printed in the console is the following:
15395409456370 | 15395397323226 | 12133144
15395410416178 | 15395410090933 | 325245
15395411137449 | 15395410835563 | 301886
15395411806342 | 15395411515427 | 290915
15395412389234 | 15395412097611 | 291623
15395412780660 | 15395412529737 | 250923
15395413168193 | 15395412912315 | 255878
15395413538738 | 15395413302679 | 236059
15395413948214 | 15395413665792 | 282422
15395414329376 | 15395414083762 | 245614
You will notice that the very first 'run time' value (the third value) is significantly greater in the first reading of the file than subsequent readings. No matter how many times I run the program, or how many times I make the for loop run (100 or 100000) the first value is always much greater. Why is this happening? Can I prevent it from happening? Is JAVA being smart and storing the values from the file and it isn't actually re-reading the file each time?
I am very curious...