代码与细节(一)

在用到 Java17的新特性 Unmodifiable Lists 时不知道你是否和我有同样的惊讶

为什么弄了这么多重载方法?

先说结论:为了性能。

其实一细想,都能想明白:varargs(可变参数) 的背后是数组的内存分配和初始化,相比正常的传参涉及更多的内存开销。

所以任何便利都是有代价的。下面列出一段大神兼偶像 Joshua Bloch 《Effective Java - Third Edition》Item53:Use varargs judiciously 的原文作为佐证:

Exercise care when using varargs in performance-critical situations. Every invocation of a varargs method causes an array allocation and initialization. If you have determined empirically that you can't afford this cost but you need the flexibility of varargs, there is a pattern that lets you have your cake and eat it too.
Suppose you've determined that 95 percent of the calls to a method have three or fewer parameters. Then declare five overloadings of the method, one each with zero through three ordinary parameters, and a single varargs method for use when the number of arguments exceeds three:

public void foo() { }
public void foo(int a1) {}
public void foo(int a1, int a2) { }
public void foo(int a1, int a2, int a3) {}
public void foo(int a1, int a2, int a3, int... rest) { }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值