CGI Language-Specific Optimization Tips
While any programming language that includes the concept of standard in and standard out can be used to write a CGI, some languages are intrinsically more suited to the task than others. In this section, I will review the most common CGI languages (sh, Perl, and C), point out their strengths and weaknesses for CGI use, and give some language-specific optimization tips. But first, here are a few performance tips general to all languages:
Keep loops small.
Use table lookups rather than calculation, where practical.
Use integer rather than floating point math.
Avoid dynamic memory allocation.
Profile your code and optimize the most-used parts.
Shell Scripts
Unix Bourne shell scripts have the
advantages of portability across Unix systems, easy file
manipulation, and filtering. However, shell scripts are very slow to
execute because they are interpreted and because they rely on other
Unix programs for advanced functionality, with the result that
sh
scripts tend to fork
a lot
of new processes. This consumes time and resources. For example, if
you wanted your sh
CGI to search in all the
files in the current directory for the word “foo” and
output a sorted list of the results, eliminating duplicate lines, the
programming is remarkably easy. Here is an entire CGI program that
does exactly that:
#!/bin/sh echo "Content-type: text/plain" echo grep -h foo * | sort | uniq
Although the time it took to write this program is negligible, we pay a large price at ...
Get Web Performance Tuning now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.