<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.fp.js"></script>
var data = Array(100).fill().map(function(i) {
return {
counter: i
}
});
function isOdd(num) {
return num % 2 === 1;
}
function square(num) {
return num * num;
}
function lessThanThreeDigits(num) {
return num.toString().length < 3;
}
var result = R.pipe(
R.map(x => x.counter),
R.filter(isOdd),
R.map(square),
R.filter(lessThanThreeDigits)
)(data);
var a = _.pick(data, 'counter')
var b = _.filter(a, isOdd)
var c = _.map(b, square)
var d = _.filter(c, lessThanThreeDigits)
var result = _.flow(
_.map(_.pick('counter')),
_.filter(isOdd),
_.map(square),
_.filter(lessThanThreeDigits),
)(data);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
ramda | |
lo | |
lodash fp |
Test name | Executions per second |
---|---|
ramda | 61000.0 Ops/sec |
lo | 63468.4 Ops/sec |
lodash fp | 14274.6 Ops/sec |
This benchmark tests the performance of three different approaches to processing an array of objects in JavaScript:
Options Compared:
ramda
Test): Uses Ramda, a functional programming library known for its immutability and concise syntax. It chains together functions like map
, filter
, and square
using R.pipe
for data transformation.lo
Test): Employs Lodash, another popular library offering utility functions for array manipulation. It uses a more imperative style with individual function calls like _.pick
, _.filter
, and _.map
. lodash fp
Test): Similar to Ramda's approach, this uses Lodash's _.flow
function to chain together transformations like _.map(_.pick('counter'))
, _.filter(isOdd)
, etc. This highlights the power of functional composition for readability and potential performance gains.Pros/Cons:
Ramda:
Lodash:
Lodash Flow:
Other Considerations:
data
array significantly impacts execution time.Alternatives:
Besides Ramda and Lodash, other options for functional programming in JavaScript include:
Let me know if you'd like to dive deeper into any specific aspect!