有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用字符串匹配或布尔标志进行性能优化

我有一个函数,它检查几个参数的有效性,并返回一个包含错误消息的字符串。在调用函数中,我要做的是使用errorString.equals("")方法检查返回的字符串是否为空。如果不为空,则显示错误消息。我听说字符串比较在Java中代价很高。我可以使用的另一种方法是,错误检查函数返回布尔值而不是字符串,并使errorString成为全局字符串,调用函数检查返回的布尔值,并在需要时显示errorString。我希望通过进行此更改可以提高多少性能?假设我的函数每分钟被调用1000次

编辑:- 例如:-

    public void callingFunction(){
    /*
    some operations....
     */
    String errors=checkErrors(param1,param1,param3,param4,param5);
    if(!"".equals(errors)){
        System.out.println(errors);
    }
}
public String checkErrors(String param1,String pram2,String param3,String pram4,String param5){
    String errors="";
    if(param1 == null)
        errors +="param1 is null";
    if(param1.equals(""))
        errors +="param1 is empty";
    /*
    A lot more validity checks...
     */
    return errors;
}

共 (2) 个答案

  1. # 1 楼答案

    我认为你完全错了

    • 如果只需要检查一个条件,则返回一个boolean。否则:
    • 如果您不需要提供故障本身以外的任何信息,则返回一个标志字,该标志字的各个位指示各种可能的错误(如果已设置)
    • 否则,您应该抛出各种类型的异常
  2. # 2 楼答案

    根据我的评论,除非有benchmark/performance profile表明存在问题,否则没有性能问题。实际上,在大多数应用程序级代码中,除非性能界限发生变化,否则大多数代码都是“足够快的”——干净地编写代码,并遵循97/31规则

    In the calling function what i am doing is that checking whether the returned string is empty using errorString.equals("") method. If it is not empty, error message is shown. I have heard that string comparison is costly in JAVA.

    嗯,不String.equals一般来说并不是不必要的“昂贵”,而且在这种特殊情况下肯定不是String.equals对于长度相同的两个任意字符串是O(n),但对于长度不同的字符串是O(1)

    String.equals所做的第一件事(在检查null之后是第二件事)是比较两个字符串的长度,长度存储在一个简单的整数变量中。如果长度不相等,可以立即确定字符串不相等:长度为0的唯一字符串是空字符串

    也就是说,除了一些额外的指令(JIT很可能会内联方法调用),它还具有检查布尔变量的同等性能特征

    另外,不要忘记现代CPU的速度非常快。我的CPU是“旧”的,工作频率为22亿赫兹;1000次操作/分钟仅为16赫兹


    197/3规则(courtesy of D. Knuth):

    Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs .. We should forget about small efficiencies, say about 97% of the time .. Yet we should not pass up our opportunities in that critical 3%. A good programmer will [..] be wise to look carefully at the critical code; but only after that code has been identified ..