开发者

PHP - Over-commenting?

I recently started working on a small CMS. I usually develop .NET applications in C#, and I'm very used to commenting my fields and methods. My friend told me earler that having comments in PHP scripts is quite bad, since PHP is dynamic and parsed when requested, so having to parse the comments will take longer.

Does this statement apply to my situation, which is commenting every method and field?

Example of one of my classes:

<?php
/* 
 *     jWeb
 *     Copyright (C) 2010 AJ Ravindiran
 * 
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     This program is distribu开发者_如何学Goted in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/**
 * Controls database connections.
 *
 * @author AJ Ravindiran
 * @version 1.0.0 Jan-02-2010
 */
class database {
    /**
     * The database connection ip address.
     * @var string
     */
    private $host = "";

    /**
     * The database user's name.
     * @var string
     */
    private $username = "";
    /**
     * The database user's password.
     * @var string
     */
    private $password = "";

    /**
     * The database that this instance will write to, and read from.
     * @var string
     */
    private $database = "";

    /**
     * Holds the mysql connection instance.
     * @var resource
     */
    private $connection = null;

    /**
     * Whether the instance is connected to the specified database.
     * @var bool
     */
    private $connected = false;

    /**
     * Constructs a new database instance.
     * @param string $host The database server host.
     * @param string $port The database server port.
     * @param string $username The database's username authentication.
     * @param string $password The username's specified password.
     */
    public function __construct($host = "localhost", $username = "root", $password = "") {
        $this->host = $host;
        $this->username = $username;
        $this->password = $password;
    }

    /**
     * Connects to the given database.
     * @param string $database
     */
    public function connect($database) {
        $this->database = $database;

        // TODO: handle errors.
        $this->connection = @mysql_connect($this->host, $this->username, $this->password) or die();
        @mysql_select_db($this->database, $this->connection) or die();

        /*
         * If the connection was successful, we can now
         * identify that the connection is sustained.
         */
        if ($this->connect != null) {
            $this->connected = true;
        }
    }

    /**
     * Gets the specified connection details from this instance.
     * @param boolean $show_details
     * @return string The connection string.
     */
    public function getConnectionString($show_details = false) {
        if ($show_details) {
            return "database[host=" . $this->host 
                    . ", port=" . $this->port
                    . ", user=" . $this->username
                    . ", pass=" . $this->password
                    . ", database=" . $this->database . "]";
        } else {
            return "database[host=" . $this->host
                    . ", port=" . $this->port . "]";
        }
    }
}
?>


The other commenters here are exactly right regarding performance. Performance should not be a consideration when commenting in code.

However, to comment on your specific example, I believe your class does have too many comments in it. For example, take a look at this field:

/**
 * The database user's name.
 * @var string
 */
private $username = "";

There's a lot of "visual noise" there and the comment doesn't really explain anything anyway. You have 4 lines worth of comments that don't tell the reader any interesting details. If you want to put a comment there it should explain something interesting about the code, not just repeat what the code does. For example:

/**
 * The database user's name. This field has to be 5 to 10 characters long. It
 * is not required if the connection security is disabled.
 * @var string
 */
private $username = "";

To pick on another example, take a look at this comment:

/** 
 * Gets the specified connection details from this instance. 
 * @param boolean $show_details 
 * @return string The connection string. 
 */
public function getConnectionString($show_details = false) {
    ...

This comment is a good start, but it's missing some crucial information: What exactly does the show_details parameter do? What details will be missing if it is not enabled? Or what will be included when it is enabled?

Comments are not fundamentally bad, and more comments is not always worse than fewer comments. It's important to have the right comments!


Your friend speaks silliness.

PHP is dynamic and must parse scripts as requested, but the time it takes to parse comments is negligible (because as soon as it encounters a comment it drops to the next relevant line; it's probably only slightly more overhead than whitespace) and the value of the comments to yourself and future maintainers of the system is much, much greater than any potential performance hit.

Feel free to comment liberally.

You can speed up PHP quite a lot by using an opcode caching mechanism like APC or eCache, though. Invest your effort and time into real solutions like that, not presumed silliness like omitting comments.


That's b*llshit, the amount of comments has nothing or very little to do with actual processing times, as the comments aren't parsed.

The more meaningful comments you have in your code, the better it will be for the next who has to maintain it.

The commenting style presented in your code sample is exemplary as you are using comments where comments are needed and you are using the phpdoc syntax, which will make creation of documentation a breeze.

Some might critizise the commenting of every class variable, but in my opinion, that's the point of using phpdoc syntax that every meaningful variable, method and class has an explanation.


Comment as much as you need to, to make the meaning of your code clear. The time you gain, if any, by not parsing comments is overwhelmed by the pain of maintaining opaque code.

That said, comments should be meaningful, and you have a bit more than is strictly necessary. For example:

/**
 * The database that this instance will write to, and read from.
 * @var string
 */
private $database = "";

I question whether the large comment here adds anything to your code.


You have commenting and commenting. Especially starters like to translate every single line of code into a "human readable language".

// Assign "a" to x.
$x = "a";

// Do stuff with x and get y.
$y = do_stuff($x);

// Return y.
return $y;

While experts (bit) more experienced programmers often just do:

// Do stuff with "a" and return it.
$x = "a";
$y = do_stuff($x);
return $y;

or even

// Do stuff with "a" and return it.
return do_stuff("a");

Needless to say that the first is an example of "over-commenting". Those kind of comments can however also perfectly be placed as a function-comment. Just write self-explaining code, e.g. do not use variables like $x, but give it a noun name, like $speed or so and give functions a verb name, like increment_speed() or so. This way you can just leave all comments inside the function away which are already explained by the code itself.

"Over-commenting" however doesn't harmfully impact performance. Unless it's a zillion of comment lines on a single line of code, especially if it is an interpreting language. Compiled languages such as Java doesn't suffer from this; comments are already removed after compilation.

Update: you included a code example; it is indeed overdone to comment private properties, especially if they already have a self-explaining name. The comments on the functions are okay.


Don't listen to your friend. You shouldn't worry about micro-performance optimizations unless you have profiled your application and found that it spends most of its time parsing comments in your PHP files (and most likely it's not there.... you would need many, many megabytes of comments for it to be noticable).

There are many other ways that you can make your application run slowly, such as using the wrong data structures or incorrectly configuring your database. Removing all the comments just confuses other programmers makes performance hurting errors (and more importantly: logical errors) more likely to happen.


I'd consider that a case of absurdly counterproductive premature micro-optimization:

  • Ignoring the comments is just about the least complex and time-consuming part of parsing
  • If performance is important, you'll want to use a server that caches the PHP bytecode anyway, making the parsing overhead irrelevant
  • Never trade of maintainability for performance unless you have hard data that proves you have a performance problem and where exactly it lies


If performance is a priority for your PHP code, you should use a bytecode cache such as:

  • APC
  • eAccelerator
  • XCache
  • Zend Server
  • Windows Cache Extension for PHP

Bytecode caches store code that has been parsed and compiled to bytecode. Subsequent execution of the same PHP page doesn't have to parse the code, let alone the comments.

Therefore, code comments impact performance only in application deployments that don't care about performance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜