"Replace array subset" is typically very fast.
Your main problem is the use of global variables inside a loop. I cannot test because I don't have a data file, but the attached modification should speed it up a bit. It limits the constant reading and writing of globals.
You might also consider reading all records outside the loop, replace the while loop with a for loop, and autoindex on the array of records. You should be able to calculate how many records are in the file from the file size.