var header = "application/json; utf-8";
var isApplicationJsonSplit = (text) =>
text !== undefined &&
text
.split(";")
.map((str) => str.trim())
.some((str) => str === "application/json");
var isApplicationJsonIncludes = (text) =>
text !== undefined &&
text.includes('application/json');
isApplicationJsonSplit(header);
isApplicationJsonIncludes(header);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
isApplicationJsonSplit | |
isApplicationJsonIncludes |
Test name | Executions per second |
---|---|
isApplicationJsonSplit | 2579145.2 Ops/sec |
isApplicationJsonIncludes | 4144491.0 Ops/sec |
This benchmark compares two JavaScript functions: isApplicationJsonSplit
and isApplicationJsonIncludes
. Both functions aim to determine if a given text string represents a valid "application/json" header.
Here's a breakdown:
isApplicationJsonSplit
: This function splits the input text by semicolon (;
), trims each part, and checks if any of the trimmed parts are equal to "application/json".
isApplicationJsonIncludes
: This function uses the includes()
method to directly check if the input text contains the substring "application/json".
Pros and Cons:
isApplicationJsonSplit
:
isApplicationJsonIncludes
:
Other Considerations:
Edge Cases: Both functions should handle edge cases like empty strings or malformed headers gracefully.
Performance: The benchmark results show that isApplicationJsonIncludes
is significantly faster, executing nearly twice as many times per second compared to isApplicationJsonSplit
.
Alternatives:
In this specific scenario, isApplicationJsonIncludes
offers a good balance of conciseness, readability, and performance.