<script type='module'>
import qs from 'https://cdn.skypack.dev/query-string';
window.qs = qs
</script>
window.string = 'hola=mundo&soy=david'
window.parseQuery = (query) => {
const searchParams = new URLSearchParams(query);
const result = {};
for (const [key, value] of searchParams) {
if (key in result) {
const current = result[key];
if (Array.isArray(current)) {
current.push(value);
} else {
result[key] = [current, value];
}
} else {
result[key] = value;
}
}
return result;
};
qs.parse(string)
parseQuery(string)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
query-string | |
URLSearchParams |
Test name | Executions per second |
---|---|
query-string | 207778.2 Ops/sec |
URLSearchParams | 384756.9 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The benchmark compares two approaches to parsing query strings: query-string
and URLSearchParams
. We'll explore what each approach does, their pros and cons, and other considerations.
Library: URLSearchParams
URLSearchParams
is a built-in JavaScript library that provides a convenient way to parse and manipulate URL query strings. It was introduced in ECMAScript 2015 (ES6) as part of the URL API.
The parseQuery
function provided in the benchmark preparation code creates an instance of URLSearchParams
from a query string, which allows you to easily access and manipulate the key-value pairs.
Pros:
Cons:
Library: query-string
query-string
is a popular third-party library that provides an implementation of the URLSearchParams
interface. It's widely used in production code and offers more flexibility than the built-in JavaScript implementation.
The benchmark uses import qs from 'https://cdn.skypack.dev/query-string';
to import the qs
object, which provides the same functionality as URLSearchParams
.
Pros:
Cons:
Comparison
The benchmark compares the execution speed of two functions: qs.parse(string)
and parseQuery(string)
. The first function uses the built-in JavaScript URLSearchParams
implementation, while the second function uses the third-party query-string
library.
Based on the latest benchmark result, query-string
is slightly faster than URLSearchParams
in this specific use case. However, it's essential to note that this may not be true for all scenarios or implementations.
Other Considerations
When choosing between these two approaches:
URLSearchParams
) might be sufficient.query-string
library.Other Alternatives
If you're looking for alternative implementations or approaches:
URL
API, which provides more control over the parsing process.