Introduction to the

Benchmark, benchmarking, jsPerf

One of the most common comments in the gracefully inserted array article was “Can we benchmark?” It’s not that we don’t like benchmarking, it’s that hardware is performing faster and faster these days, and sometimes certain actions are not the main cause of performance problems, which is certainly not the reason why we don’t write good code.

Writing code should still balance elegant legibility with performance, doing the right thing for the right scenario. But since we’re all talking about benchmarks and I happen to have no idea what TO write about so let’s talk about benchmarks.

To err is human, and three starlings are always with me. – well it’s me

Testing is an essential part of medium to large and open source projects. Good testing can help us write better quality code by finding errors in hypothetical scenarios, and is also a mediator in collaborative development. Testing is a university in development that can’t be explained in a single article.

Talk is cheap, Show me the code. — Linus Torvalds

The benchmarks chosen for this article are just a small subset of testing, and this article gives you a taste of some simple concepts and testing tools. After learning when encounter wild program ape say words: “nonsense little say, put horse come over”, please copy keyboard to open benchmark test tool shout: “I is Yan person Zhang Yide, who dare to fight with me?” .

Flip a coin

It is obviously wrong to conclude that the probability of getting heads is 100% after flipping a coin. Our math teacher taught us the law of large numbers: “We need enough data and enough samples to draw a conclusion.” When you flip a fair coin enough times the probability of getting heads should approach 50 percent indefinitely, as in the case of the experimental coin toss benchmark you can’t just record the running time of the code once, you need to do it enough times.

Scared the crab

The scientist took a crab out of its cage, put it on the ground, and yelled at it. The crab was so frightened that it ran around in any way it could. The scientist then disassembled the crab’s legs and repeated the procedure. He continued to growl, but the crab didn’t move, it was very calm and calm, and concluded that the crab’s ears were on its legs.

This little joke we should have heard, did not consider the crab to escape is to use legs. The three concepts that come up when you do biological control experiments independent variables and dependent variables, independent variables, control them to get real results. The influence variables of the benchmark test can be the lower running speed caused by the mobile phone entering the power saving mode, the inconsistent testing environment at a certain moment caused by irrelevant software running on the computer, or the inconsistent initial state of the code. Examples are as follows:

/ / code
let a = [1.2.3.4];
a.push(5);

/ / code 2
let b = [1.2.3.4.5.6.7.8];
b = [...b, 9];
Copy the code

Testing the above two pieces of code doesn’t tell you which one is better, because the size of the initial array is different and the larger the array, the slower the operation.

Benchmark

The two simple examples above help you understand some of the basic points of benchmarking. In addition to taking advantage of browser features to tune the code during development, sometimes different code writing methods can lead to different performance. There are four different ways to insert data at the end of an array. Which of these methods will make your code elegant, easy to read, and fast? Use Benchmark to help determine your results.

The installation

npm i --save benchmark
Copy the code

use

  • addInterface adds test code.
  • onThe interface inserts code into the test cycle.
  • runRun the code.

example

code
let suite = new Benchmark.Suite;

suite
    .add('#1 assign to array length '.() = > {
        let arr = [1.2.3.4.5];
        arr[arr.length] = 6;
    })
    .add('#2 利用 Array.prototype.push 方法'.() = > {
        let arr = [1.2.3.4.5];
        arr.push(6);
    })
    .add('#3 利用 Array.prototype.concat 方法'.() = > {
        let arr = [1.2.3.4.5];
        arr = arr.concat(6);
    })
    .add('#4 use the spread operator '.() = > {
        let arr = [1.2.3.4.5];
        arr = [...arr, 6];
    })
    .on('start'.(event) = > {
        // Before the entire test runs
        console.log('Insert data into the end of array');
    })
    .on('cycle'.(event) = > {
        // After each test code is run
        console.log(String(event.target));
    }).on('complete'.() = > {
        // After the test is complete
        console.log('The quickest way is.' + suite.filter('fastest').map('name'));
    }).run({ 'async': true })
Copy the code
The output
#1 Ops/SEC ±0.61% (87 runs sampled) #2 Ops/SEC ±0.61% (88 runs sampled Concat method x 2,373,044 ops/ SEC ±1.00% (83 runs sampled) #4 Spread operator x 2,405,217 The fastest method to ops/ SEC ±0.72% (91 runs sampled) is #2 using the array.prototype.push methodCopy the code

jsPerf

A benchmarking library. As used on jsPerf.com.

JsPerf, a benchmark-based convenience benchmarking site, is mentioned in the project description in the Benchmark repository. Once logged in using Github, fill out the data from the create form to generate the benchmark.

Benchmark examples are linked in jsPerf to insert data into the end of an array. JsPerf makes it easy to share (as it is now) and open tests in different browsers. The following is a simple translation of the page name for the convenience of students who are not good at English:

Personal information

noun explain
Your details Personal information, optional
Name Author’s name
Email Author email, due to generated avatar
URL The project address

Case information

noun explain
Test case details Case information
Title The title
Slug Slug, the website, will be spliced togetherjsperf.com/slug
Description Project description

preload

noun explain
Preparation code preload
Preparation code HTML The DOM structure required for the project and the introduction of external scripts
Define setup for all tests The operations that will be performed before each test are the configurations in benchmark.setup, such as initializing variables.
Define teardown for all tests What happens after each test is the configuration in benchmark.teardown, such as clearing variables.

Code snippets to compare

If you have a test code box that you don’t need, you just empty it out and save it and it will delete itself.

noun explain
Code snippets to compare Code snippets to compare
Title Test code section title
Async Whether the code segment is asynchronous
Code Code to test
Add code snippet Adding test code
Save test case save

The test page

noun explain
Run test Run the test
Testing in … Test the browser and its version, and the operating system and its version
Ops/sec Number of code executions per second, the higher the better
You can edit these tests or add even more tests to this page by appending /edit to the URL. You can modify the test code by clicking on this link, but you can’t change the slug
Compare results of other browsers All browser test results
Chart type Data display: bar chart, line chart, pie chart and table
Filter Browser environment

At the end

Also don’t hurry to take the keyboard and wild programmer war 300 rounds, hit full experience upgrade fly fairy become ancient programmers.

Grow up together

In the confused city, there is always a partner to grow up together.

  • You can click on this if you want more people to see the articlegive a like.
  • If you want to inspire your mistress thereGithubGive aLittle stars.
  • If you want to communicate more with small two add wechatm353839115.

PushMeTop originally contributed to this article