BeanUtils.copyProperties 和 MapStruct 到底差多少?类型不同、名字不同、null 值各会怎样?漏映射能不能在编译期发现?这篇用同一对 7 个字段的对象,在本机逐个测。
Spring BeanUtils.copyProperties:name=张三, age=null, score=99, nick=null, active=true, addr=北京, note=null;addr 是同一个对象:true Commons BeanUtils.copyProperties:name=张三, age=30, score=99, nick=null, active=true, addr=北京, note=null;addr 是同一个对象:true MapStruct(只映射了 nickName → nick):name=张三, age=30, score=99, nick=三儿, active=true, addr=北京, note=null;addr 是同一个对象:true
类型不同、名字不同、null 值的表现。
编译退出码 0 demo/M.java:3: warning: Unmapped target property: "nick". 3 warnings
MapStruct 漏映射有警告。
编译退出码 1 demo/M.java:3: error: Unmapped target property: "nick". 1 error 1 warning
ReportingPolicy.ERROR 让构建失败。
第 1 轮(整套基准各跑一遍)
manual:5.6 ± 0.2 ns/op
mapstruct:4.4 ± 0.1 ns/op
springBeanUtils:227.9 ± 8.5 ns/op
commonsBeanUtils:7428.5 ± 165.6 ns/op
第 2 轮(整套基准各跑一遍)
manual:5.5 ± 0.2 ns/op
mapstruct:4.4 ± 0.2 ns/op
springBeanUtils:225.7 ± 15.5 ns/op
commonsBeanUtils:7486.3 ± 248.3 ns/op
两轮平均:manual 5.6 ns;mapstruct 4.4 ns;springBeanUtils 226.8 ns;commonsBeanUtils 7457.4 ns
相对 MapStruct 的倍数:springBeanUtils 51.3 倍;commonsBeanUtils 1688.2 倍手写、MapStruct、Spring、Commons 四者相差几十到上千倍。