为什么使用 Collection.empty[T] 而不是 new Collection[T]() [英] Why use Collection.empty[T] instead of new Collection[T]()

查看:44
本文介绍了为什么使用 Collection.empty[T] 而不是 new Collection[T]()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有充分的理由使用 Collection.empty[T] 而不是 new Collection[T]()(或相反)?还是只是个人喜好?

I was wondering if there is a good reason to use Collection.empty[T] instead of new Collection[T]() (or the inverse) ? Or is it just a personal preference ?

谢谢.

推荐答案

调用 new Collection[T]() 每次都会创建一个新实例.另一方面,Collection.empty[T] 很可能总是返回相同的单例 object,通常在某处定义为

Calling new Collection[T]() will create a new instance every time. On the other hand, Collection.empty[T] will most likely always return the same singleton object, usually defined somewhere as

object Empty extends Collection[Nothing] ...

这会快得多.这仅适用于不可变集合,每次调用 empty 时,可变集合都必须返回一个新实例.

which will be much faster. This is only possible for immutable collections, mutable collections have to return a new instance every time empty is called.

这篇关于为什么使用 Collection.empty[T] 而不是 new Collection[T]()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆