是否应在每次使用时创建番石榴拆分器/联接器? [英] Should Guava Splitters/Joiners be created each time they are used?

查看:40
本文介绍了是否应在每次使用时创建番石榴拆分器/联接器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Guava包含用于拆分和连接字符串的实用程序,但是它需要实例化Splitter/Joiner对象.这些是小对象,通常只包含要在其上拆分/加入的字符.维护对这些对象的引用以重用它们是一个好主意,还是最好在需要时创建它们并让它们被垃圾回收?

Guava contains utilities for splitting and joining Strings, but it requires the instantiation of a Splitter/Joiner object to do so. These are small objects that typically only contain the character(s) on which to split/join. Is it a good idea to maintain references to these objects in order to reuse them, or is it preferable to just create them whenever you need them and let them be garbage collected?

例如,我可以通过以下两种方式实现此方法:

For example, I could implement this method in the following two ways:

String joinLines(List<String> lines) {
  return Joiner.on("\n").join(lines);
}

OR

static final Joiner LINE_JOINER = Joiner.on("\n");

String joinLines(List<String> lines) {
  return LINE_JOINER.join(lines);
}

我发现第一种方法更具可读性,但是每次调用该方法时创建一个新的Joiner似乎都是浪费的.

I find the first way more readable, but it seems wasteful to create a new Joiner each time the method is called.

推荐答案

老实说,这听起来像是我的过早优化.我同意@Andy Turner的观点,写出最容易理解和维护的内容.

To be honest, this sounds like premature optimization to me. I agree with @Andy Turner, write whatever is easiest to understand and maintain.

如果您打算在某些地方使用Joiner.on("\n"),请将其命名为常量.选择第二种.

If you plan to use Joiner.on("\n") in a few places, make it a well named constant; go with option two.

如果仅打算在joinLines方法中使用它,则常量似乎太冗长;选择选项一.

If you only plan to use it in your joinLines method, a constant seems overly verbose; go with option one.

这篇关于是否应在每次使用时创建番石榴拆分器/联接器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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