哪个更好?将整个内容作为字符串或字符串连接传递?

时间:2010-08-19 06:51:38

标签: string string-concatenation

嗨,我有20个字符串,除了类名之外,每个字符串都有相同的包结构。需要将这些字符串传递给方法。请参阅以下代码:

public static final String RECENT_MSG_        = "com.foo.xxs.RecentMessage";
public static final String PROJ_              = "com.foo.xxs.Proj";
public static final String FORECAST           = "com.foo.xxs.Forecase";
public static final String REQUEST            = "com.foo.xxs.Request";
public static final String UNAPPROVED         = "com.foo.xxs.UnApproved";
public static final String UNPOSTED           = "com.foo.xxs.Unposeted";
public static final String VACANT             = "com.foo.xxs.Vacant";
public static final String ORG_VIOL           = "com.foo.xxs.OrgViolation";
public static final String ORG_WARN           = "com.foo.xxs.OrgWarning";
public static final String EMP_VIOL           = "com.foo.xxs.EmpViolation";
public static final String EMP_WARN           = "com.foo.xxs.EmpWarning";    
public static final String TS_WARN            = "com.foo.xxs.TSWarn";
public static final String TS_VIOL            = "com.foo.xxs.TSViolation";
public static final String AGE_GROUP          = "com.foo.xxs.AgeGroup";


private void rescheduleTasks(long _taskType,String value)
{
    if(_taskType == 1000 &&(_sSchedTaskMgr.getInstance().getCurrentScheduledTaskInfo(RECENT_MSG_)==null))
    {

    // do something     
    }

}

这也可以按如下方式完成:

public static final String RECENT_MSG_        = "RecentMessage";
public static final String PACK                       ="com.foo.xxs."

并像这样连接字符串:

if(_taskType == 1000 &&(_sSchedTaskMgr.getInstance().getCurrentScheduledTaskInfo(PACK+RECENT_MSG_)==null))

哪一个更好?

2 个答案:

答案 0 :(得分:2)

它们具有相同的性能 - 连接将在编译时执行而不是执行时间,因为两个部分都是常量。原则上,常量池中的字符串将更少 - 但这不太可能产生影响。

您觉得哪个更具可读性?我不能说对我来说有很多东西 - 我不喜欢第一种形式的重复,但同样我不确定我想要在任何地方连接。

另一种选择是:

public static final String PACK               = "com.foo.xxs."
public static final String RECENT_MSG_        = PACK + "RecentMessage";

等 - 所以你在常量声明点执行连接。然后你可以在代码中使用RECENT_MSG_,就像第一个代码片段一样,但是避免按照第二个代码复制“com.foo.xxs”。

编辑:您可能要考虑的另一个选项是使用枚举。

答案 1 :(得分:1)

我会选择第一个版本,您只需让读者更容易立即看到字符串的含义以及您所引用的类别。另外, 你想要从不同的命名空间引入一个类,你就可以这样做。

相反,第二个版本引入了一些需要首先由读者解释的逻辑。

如果你选择第二个版本,请使用Jon的替代版本,这样至少你仍然可以选择从其他名称空间引入类。