Why C?

Chapter 8 - Programming Perl in C
by?Sam Tregar?
Apress ? 2002
has companion web siteCompanion Web Site

Writing Perl modules in C is a lot more work than writing them in Perl. The end result is likely to be buggier and less portable than an equivalent implementation in Perl. As such, you should be hesitant to write in C unless you have a good reason.

So, what constitutes a good reason? The best reason is simple: because you have to. There are times when Perl simply cannot do what you need done. For example, when you need to interface with a library written in C, you have no choice but to write some C code. CPAN contains numerous examples of this type of module-Tk, GD, most of the DBD drivers, and many more. When you come across a C library that provides a new service, you should consider it a great opportunity to create a new CPAN module.

A common, often misguided, reason to create Perl modules in C is to increase performance. The reasoning is misguided because the Perl interpreter itself is written in C. Thus most of what a Perl program does is already happening in highly optimized C code. You have to believe you can do better than the C gurus that created Perl to think that your module will be faster simply by being written in C.[1]

That said, sometimes you can write faster code in C than in Perl. After careful profiling and tuning, sometimes it turns out that 90 percent of your module's runtime is taking place inside a small section of code. If you can replace this piece with a call to a function written in carefully crafted C, you might realize significant gains. The watchword here is profiling: You need to find the bottleneck and be sure you can't optimize it using more conventional techniques.

One place where C does have a notable advantage over Perl in performance is in memory usage. C requires you to be entirely responsible for every memory allocation; as a result, you gain a much higher degree of control over how your data is stored. Sometimes this can be used to allow your programs to run in a much smaller amount of memory than a Perl implementation would.[2]

[1]Mark-Jason Dominus's article "Why Not Translate Perl to C?" on Perl.com contains an extended proof of this assertion. You can find the article at http://www.perl.com/pub/a/2001/06/27/ctoperl.html.

[2]But before you decide this describes your problem, make sure you check out Bit::Vector by Steffen Beyer and the many modules that use it to efficiently store data.



Writing Perl Modules for CPAN
Writing Perl Modules for CPAN
ISBN: 159059018X
EAN: 2147483647
Year: 2002
Pages: 110
Authors: Sam Tregar

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net