背景

我有一个对象数组,我需要拼接成一个字符串,最终打印出我想要的信息。第一次我的方法是使用reduce+slice,第二次我使用map+join。哪种方法更好?

1
2
3
4
5
6
7
8
9
10
// 方法1:reduce, slice
const customMsg = commandMessages.reduce((pre, cur) =>
pre + `${cur.shopCode}:${cur.message}、`, '');
message.warning(customMsg.slice(0, -1));

// 方法2:map, join
const customMsg = commandMessages
.map((item) => `${item.shopCode}:${item.message}`)
.join('、');
message.warning(customMsg)

分析

  1. 可读性

两个方法的可读性差不多,但是reduce方法和map方法的使用频率比,后者会高一点,如果非要说哪个可读性更好,方法2会好一点。

  1. 性能

github源码:

https://github.com/janice143/reduceSliceVSMapJoin

  • benchmark.js测量:npm run test:bench

代码在 test1/1_bench.js 文件中,从结果可知,reduce_slice性能更好。

  • performance api测量:npm run test:performance

代码在 test1/2_performance.js 文件中,该方法适合大的数据量,因为精度高,小样本会使得结果很大的波动。

结论

从可读性将,map会好一点。从性能讲,reduce更好一点。