Speeding up code

Status
Not open for further replies.

dominicanpapi82

Beta member
Messages
5
I know these forums aren't for code optimization, but this one is so short that I thought someone might be able to help me quickly.

I'm writing the following cgi program, and was wondering if anyone could help me know if there is a faster/better way of doing this:


Code:
open(FH,"file1.txt")     # OPEN file1.txt, ABOUT 50 LINES OF TEXT
while (my $line = <FH>) {
    print $line;   #PRINT ONE LINE AT A TIME
}
close(FH);

(INSERT INFO FROM A SHORT FORM HERE)

open(FI,"file2.txt")     # OPEN file2.txt, ABOUT 600 LINES OF TEXT
while (my $line = <FI>) {
    print $line;   #PRINT ONE LINE AT A TIME
}
close(FI);
 
In theory, converting this code to PHP should be faster, as CGI requires an external process to start up and run. Again, in theory.

As for the actual algorithm, it may be a bit more efficient to read in the entire file and call the print function once for each buffer. That will cut out all the function call overhead, which is called hundreds of times currently.
 
jaeusm said:
In theory, converting this code to PHP should be faster, as CGI requires an external process to start up and run. Again, in theory.

As for the actual algorithm, it may be a bit more efficient to read in the entire file and call the print function once for each buffer. That will cut out all the function call overhead, which is called hundreds of times currently.

Unfortunately I don't know any PHP.

For big files, I know that it might slow down the system if I print the entire file, but is 600 lines "large"?
 
The code you have posted looks nearly the same as PHP. There are a few minor differences, but nothing that you can't look up on php.net.

As for 600 lines being large, maybe. Experiment and try it both ways. See for yourself if there's any performance increase or loss. Maybe you'll want to read in 50 or 100 lines at a time before printing. Try it out.

If you're using a language that requires manual destruction of an object created on the heap that contains the file's contents, then you'll have to manually free the memory. If you're using a garbage collected language, or if your object is created on the stack, then you shouldn't have to worry about it.
 
Status
Not open for further replies.
Back
Top Bottom