在用到 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) { }
”