Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Potherca/0c10a67b12f553a13ebe62f208e97202 to your computer and use it in GitHub Desktop.
Save Potherca/0c10a67b12f553a13ebe62f208e97202 to your computer and use it in GitHub Desktop.
Amount of code for the comparison of various styles of writing a `clamp` function in PHP Raw

📝 This text is part of the article Comparison of various styles of writing a clamp function in PHP

Summary

To measure the amount of code, different metrics can be used. For now I'll use the infamous lines of code (to represent how people see the code) and tokens (to represent how the PHP parser sees the code).

Line count

Lines of code can be easily counted using phploc(1).

NCLOC(2) (100.00%) LLOC(3) Percentage subject description
6 1 16.67% 832B9C44 return min max
6 1 16.67% 60AA891E return/ternary/ternary
14 3 21.43% 7BC1F85B if, if, return;
14 3 21.43% 83C742FF if/return, if/return, return
12 3 25.00% 8389C469 if, elseif, return
12 3 25.00% CAB599E9 if/return, elseif/return, else/return
8 3 37.50% A13E087E if/return, if/return, return (shorthand)

Token count

Using the token_get_all function, it is possible to see how the PHP compiler sees the code.(4)

tokens non-whitespace tokens subject description
36 12 832B9C44 return min max
52 14 60AA891E return/ternary/ternary
54 18 A13E087E if/return, if/return, return (shorthand)
62 18 83C742FF if/return, if/return, return
66 18 7BC1F85B if, if, return;
66 18 8389C469 if, elseif, return
68 19 CAB599E9 if/return, elseif/return, else/return

Footnotes

  1. Using the following command: find . -name 'clamp.*.php' -exec sh -c 'phploc {} | grep "(LLOC)"' \; -print
  2. NCLOC = Non-Comment Lines of Code
  3. LLOC = Logical Lines Of Code
  4. find ../comparison-of-clamp-functions_55ca0e9377bbd49ee41241380e1fe3f9/ -type f -name '*.php' -not -path '*/vendor/*' -exec php ./count_tokens_in_file.php {} \;
<?php
$file = $argv[1];
$contents = file_get_contents($file);
$all_tokens = token_get_all($contents);
$tokens = array_filter($all_tokens, function ($token) {
return ! is_string($token) && (
$token[0] !== 382 // T_WHITESPACE
);
});
$name = basename($file);
$count_all = count($all_tokens);
$count = count($tokens);
echo <<<TXT
File : $name
Tokens All : $count_all
Tokens : $count
TXT;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment