<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>
var array = [Array(100)];
array.fill(1);
array.fill(Math.random() * 100.1, 2, 5, 7);
R.pipe(R.map(R.dec), R.filter(R.lt(0)))(array)
array.map(i => i - 1).filter(i => i > 0)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Ramda | |
Native |
Test name | Executions per second |
---|---|
Ramda | 444724.5 Ops/sec |
Native | 2502725.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The provided JSON represents a benchmark test between two approaches: using Ramda, a functional programming library for JavaScript, and a native implementation without any libraries.
Script Preparation Code
The script preparation code is a simple array creation:
var array = [...Array(100)];
array.fill(1);
array.fill(Math.random() * 100.1, 2, 5, 7);
This creates an array of length 100, fills the first element with the value 1, and then randomly fills a sub-array from index 2 to 6 with values between 0 and 100.
Html Preparation Code
The HTML preparation code includes a script tag that loads Ramda version 0.28:
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>
This library provides a functional programming API, allowing users to write expressive and concise code.
Test Cases
There are two test cases:
R.pipe
function to apply three transformations to the input array:R.map(R.dec)
: Decrement each element in the array by 1.R.filter(R.lt(0))
: Filter out elements less than 0 from the resulting array.array.map(i => i - 1).filter(i => i > 0)
This code maps each element in the array to its decremented value and then filters out elements less than or equal to 0.
Pros and Cons
Ramda Approach:
Pros:
Cons:
Native Approach:
Pros:
Cons:
Other Considerations
Both approaches have their trade-offs. The Ramda approach provides a more concise and expressive way of writing functional programming code, but requires an external library. The native approach is more lightweight and straightforward, but may require more boilerplate code and be less readable.
Alternative Libraries or Implementations
If you prefer to use alternative libraries or implementations for the native approach, some options include:
map
, filter
): Can be used directly on arrays without creating a separate function.Keep in mind that each alternative may have its own trade-offs and performance characteristics.