O'Reilly logo

Web Performance Tuning, 2nd Edition by Patrick Killelea

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 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 runtime. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required