Reading data into and out of a VB program is straightforward. Most folks use the Input and Put statements in a For…Next loop. However, this straightforward technique takes time. Because I am impatient when it comes to machines-and that includes computers-I use a time-tested technique to speed along the input and output of data files. The technique involves the use of strings.I use strings because Basic-type programs, including VB, make efficient use of strings. One distinct reason for using strings is that a specific size is not needed for the array definition. This provides some programming flexibility if you work with files of different lengths and formats. Also, and more to the point, data is input and output faster when the Input and Put statements move strings into and out of computer programs.Speed is the big advantage of using strings in conjunction with the Input and Put statements, in lieu of embedding the statements in a For…Next loop. The speed increase is obvious with a few simple illustrations. Start with this program listing:
Open Path$ For Binary As #1 Datarray$ = Input(31680, #1) Workarray$ = Datarray$Close
This listing inputs a string named “Datarray” and copies that string to a work string named “Workarray.” I do this to maintain the integrity of the original data. As you can see, the code opens, inputs, copies, and closes a complete file in just four computer instructions.For comparison, look at a typical code listing to read this file. This is the simplified code listing:
Open Path$ For Binary As #1 For Position = 1 to 31680 Datarray$(Position) = Input(1,#1) Next PositionClose
This example inputs data with a For…Next loop. Although the number of programming lines may be relatively small, the number of computer instructions is large. To input the same file with a For…Next loop, the For, Next, and Input statements each need to be executed 31,680 times. That’s a whole heap of instructions when compared to executing the Input statement just once. The speed implication is obvious.My programming philosophy to output data follows the same technique-eliminate data loops where possible. This example shows how this is easily accomplished without a data loop:
Open Path$ For Binary As #1 Put #1,,Workarray$Close
Path$ is the output location and name of the file. Workarray is the string that holds the data to save.In summary, it is important to limit the length of For…Next and Do loops in any language. Long loops for I/O are real speed killers.