Dear, hello, everyone. I am “Front-end Xiaoxin”. 😇 has been engaged in front-end development and Android development for a long time


Writing Background:

We often encounter such a problem in the development process, there are many implementations of the same function, but which plan to choose, which plan is the best, the shortest time? In addition to what is written in books and what others say, we are better off using data. Seeing is believing

Benchmarks:

Benchmark testing refers to the quantitative and comparable testing of a certain performance index of a class of test objects through the design of scientific testing methods, testing tools and testing systems. — Baidu Encyclopedia

useBenchmark.js:

1. Dependencies required for installation:

{
    "benchmark": "^ 2.1.4." "."chalk": "^ 4.1.0." "."console-table-printer": "^ 2.10.0"."microtime": "^ 3.0.0"."ora": "^ 5.1.0"
}
Copy the code

2. Write the main structure of benchmark:

  1. Add test cases
  2. Set up to monitor
const Benchmark = require("benchmark");
const suite = new Benchmark.Suite();
const ora = require("ora");
const chalk = require("chalk");
const { getRows, p, addRow } = require("./utils");
const { description } = Benchmark.platform;
const spinner = ora();

console.log(chalk.green(description));
spinner.start(chalk.grey("Testing ..."));

const cases = function (cases) {
  // TODO adds case
  // TODO sets the listener
  return suite;
};

module.exports = {
  cases,
};
Copy the code

Note: You can then write test cases directly, not the main structure

3. Add a test case using the Benchmark add function:

cases.forEach((c) = > {
    const key = Object.keys(c)[0];
    suite.add(key, c[key]);
});
Copy the code

4. Set up listening to output test results:

Summarize the test results of each test case and present the feedback in tabular form

suite
    .on("cycle".function (event) {
      spinner.succeed(chalk.green(String(event.target)));
      spinner.start(chalk.grey("Testing next case ..."));
    })
    .on("complete".function () {
      spinner.succeed(chalk.green("Test completed"));
      getRows(this.filter("successful")).forEach((row) = > {
        addRow(row, row.case === this.filter("fastest").map("name") [0]);
      });
      p.printTable();
    });
Copy the code

5. Terminal output table:

HZS column is used for sorting, so it is hidden. Hz column is not clear why it failed to sort after being converted to Number

const p = new Table({
  columns: [{name: "case".title: "Test Case" },
    { name: "hz".title: "Executions per second" },
    { name: "rme".title: "Relative error" },
    { name: "sampled".title: "Total number of executions" },
    { name: "conclusion".title: "Conclusion"},].sort: (r1, r2) = > Number(r1.hzs) - Number(r2.hzs),
  disabledColumns: ["hzs"]});Copy the code

6. Table row data integration:

  1. Column 1: Test case names
  2. Column 2: Number of use cases executed per second, the higher the better
  3. Column 3: Relative error
  4. Column 4: The actual number of times the use case was executed
  5. Column 5: Conclusion: The use case marked fastest was the best
getRows: function (events) {
    const result = [];
    Object.keys(events).forEach((key) = > {
      if (/^\d{0,}$/g.test(key)) {
        const {
          name,
          hz,
          stats: { sample, rme },
        } = events[key];
        const size = sample.length;
        result.push({
          case: name,
          hz: Benchmark.formatNumber(hz.toFixed(hz < 100 ? 2 : 0)),
          hzs: hz,
          rme: `\xb1${rme.toFixed(2)}% `.sampled: `${size} run${size == 1 ? "" : "s"} sampled`}); }});return result;
  },
Copy the code

7. Test case writing:

Start the benchmark using the run function after loading the array of multiple case codes to be tested

require(".. /src")
  .cases([
    {
      "RegExp#test": function () {
        /o/.test("Hello World!"); }, {},"String#indexOf": function () {
        "Hello World!".indexOf("o") > -1; }, {},"String#match": function () {!!!!!"Hello World!".match(/o/);
      },
    },
  ])
  .run({ async: true });
Copy the code

8. Preview test results

The test case with the highest number of executions per second is optimal, and we can see that the optimal solution to finding characters is to use the indexOf function. Is that how you do it?

Article source code:

  1. benchmark-javascript

Other schemes:

  1. Jsbench: Web edition Benchmarking, Inspired by Benchmarks. js, Jsperf.com and Jsfiddle.com
  2. Jsperf: It should be an old benchmark website. It is currently server 500, but I haven’t been able to open it. Github can be built and used by itself.

Welcome to follow my public account “Front-end Xiaoxin students”, the first time to push original technical articles.