let s10MB = "0123456789".repeat(1000*1000);
var strings10MB = Array.from(Array(20)).map(o=>s10MB + String.fromCharCode(32+~~(Math.random()*96)));
function hashString(input) {
var encoder = new TextEncoder();
return crypto.subtle.digest('SHA-1', encoder.encode(input)).then(function (hashBuffer) {
var hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
});
}
const s1 = strings10MB[~~(strings10MB.length*Math.random())];
const s2 = strings10MB[~~(strings10MB.length*Math.random())];
const b = s1 === s2;
const s1 = strings10MB[~~(strings10MB.length*Math.random())];
const s2 = strings10MB[~~(strings10MB.length*Math.random())];
const hash1 = hashString(s1);
const hash2 = hashString(s2);
const b = hash1 === hash2;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
=== | |
SHA-1 |
Test name | Executions per second |
---|---|
=== | 21939.2 Ops/sec |
SHA-1 | 141.9 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Purpose
The goal of this benchmark is to compare two approaches for checking if two strings are equal: a simple string comparison using the ===
operator, and a hash-based approach using the SHA-1 algorithm. The benchmark aims to determine which approach is faster and more efficient in terms of execution time.
Options Compared
There are two options being compared:
===
): This method uses the equality operator (===
) to compare two strings. It's a straightforward approach that works well for most cases, but may be slow or inaccurate for very large or complex strings.===
operator. Hash-based approaches are often used in situations where data integrity is critical, as small changes to a string can result in significantly different hashes.Pros and Cons
Simple String Comparison (===
)
Pros:
Cons:
Hash-Based Approach (SHA-1)
Pros:
Cons:
Library and Purpose
The crypto
library is used in the benchmark to implement the SHA-1 algorithm. The crypto.subtle.digest()
function is used to calculate the hash of a given input string.
Special JS Feature/Syntax
None mentioned, but it's worth noting that this benchmark uses ES6+ syntax (e.g., arrow functions, template literals) and assumes the use of modern JavaScript features.
Other Considerations
When choosing between these two approaches, consider the following:
===
) for most cases where data integrity is not critical.Alternatives
Other alternatives to consider: