Java: Comparing ints and Strings - Performance

后端 未结 3 870
孤街浪徒
孤街浪徒 2020-12-18 19:33

I have a String and an int, lets say: String str = \"12345\"; and int num = 12345;. What is the fastest way of seeing if they are the same, s

相关标签:
3条回答
  • 2020-12-18 19:35

    I think num == Integer.parseInt(str) is a better way of doing comparison. Because str.equals("" + num) this is not the ideal way how you should compare integer values and also it will create unnecessary String constant objects in the String pool (which hampers performance).

    0 讨论(0)
  • 2020-12-18 19:43

    Guess you might also be able to use this to compare........

    int p = 1234;
    String Int = "1234";
    String string = String.valueOf(p);
    System.out.println(string + Int);
    System.out.println(string.equals(Int));
    code here
    
    0 讨论(0)
  • 2020-12-18 19:52

    num == Integer.parseInt(str) is going to faster than str.equals("" + num)

    str.equals("" + num) will first convert num to string which is O(n) where n being the number of digits in the number. Then it will do a string concatenation again O(n) and then finally do the string comparison. String comparison in this case will be another O(n) - n being the number of digits in the number. So in all ~3*O(n)

    num == Integer.parseInt(str) will convert the string to integer which is O(n) again where n being the number of digits in the number. And then integer comparison is O(1). So just ~1*O(n)

    To summarize both are O(n) - but str.equals("" + num) has a higher constant and so is slower.

    0 讨论(0)
提交回复
热议问题