See https://codingchallenges.fyi/challenges/challenge-wc
This has been implemented in php - as vanilla as I can stand!
Initially, this was implemented as a procedural single-file solution, then re-implemented using OOP.
Both versions are included in this repository:
- Procedural version:
ccwc.php
- OOP version:
ccwc
strict_mode
is enabled throughout.
Note
ccwc
has been developed using PHP 8.4, but is backwards compatible as far as PHP 8.1
$ git clone https://github.com/mattgorle/cc_php_001_wc
$ cd cc_php_001_wc
$ composer install
$ vendor/bin/phpunit
Note
- Tests will only run on PHP 8.3 and above
- A deprecation notice will affect one of the OptionParser tests
Both the test and the class are behaving as expected and use no deprecated behaviour
The root cause has been identified within a third-party library and a pull request opened to correct the issue
As of now, this supports the following modes:
-c
: Character count-m
: Multi-byte character count-l
: Line count-w
: Word count
Input can by given by way of filenames on the CLI or via STDIN.
One or more file names can be provided as an input argument. Shell expansion works as expected.
$ ./ccwc file
$ ./ccwc file1 file2
$ ./ccwc *
Note
If more than one file is given as input, then a total is printed at the end of the output
This can be either via a pipe or redirector.
$ cat file | ./ccwc
$ ./ccwc < file
Unsurprisingly, this is roughly an order of magnitude slower than GNU coreutils.
When processing the test document, the timings are as follows:
Implementation | Wall time |
---|---|
coreutils WC | 0.007 s |
ccwc (PHP 8.4) | 0.065s |
ccwc.php (PHP 8.4) | 0.060s |
Roughly 9x slower
The OOP rewrite is ~10% slower than the procedural version when processing the 335KB test file.
Implementation | Wall time |
---|---|
ccwc (PHP 8.4) | 0.065s |
ccwc.php (PHP 8.4) | 0.060s |
However, it is 20-30% faster when processing a 33MB test file.
Implementation | Wall time |
---|---|
ccwc (PHP 8.4) | 0.7s |
ccwc.php (PHP 8.4) | 1.0s |
- No automated test coverage
- Easier to understand the code at a glance
- No large file support (limited to roughly system RAM / 4)
- Output is less authentic when compared to coreutils
wc
- Faster than OOP on smaller files, slower on larger files
- Reads the entire file into memory for processing
- Uses no third-party libraries
- Good level of automated test coverage
- Supports files of potentially any size (files are loaded in 16MB pages)
- Output closely matches coreutils
wc
- Delegates CLI argument parsing to
vanilla/garden-cli