2

I'm trying to make a game and I have a Selection class that holds a string named str in it. I apply the following code to my selection objects every 17 milliseconds.

if(s.Str == "Upgrade") {
            
}else if(s.Str == "Siege") {
        
}else if(s.Str == "Recruit") {
            
}

In other words, these selection objects will do different jobs according to their types(upgrade,siege etc...). I am using str variable elsewhere. my question is that:
Would it be more optimized if I assign the types to an integer when I first create the objects?

if(s.type == 1) {
                
}else if(s.type == 2) {
            
}else if(s.type == 3) {
            
}

This would make me write extra lines of code(Since I have to separate objects by type when I first create) and make the code more difficult to understand, but would there be a difference between comparing integers rather than comparing strings?

  • 8
    [Do not compare `String`s (or any reference-type really) with `==` unless you know exactly what you are doing and why you are doing it](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). --- ["*premature optimization is the root of all evil*" -- Donald Ervin Knuth: *Computer Programming as an Art* (1974), p. 671](https://dl.acm.org/ft_gateway.cfm?id=361612&ftid=289767) – Turing85 May 22 '21 at 12:50
  • 4
    Don't bother worrying about the difference until profiling has shown this code has a performance problem. Write code that is optimized for humans to read it. – Andy Turner May 22 '21 at 12:51
  • 2
    (also, you might want to consider using an enum instead) – Andy Turner May 22 '21 at 12:52
  • @AndyTurner thanks for advice but what is profiling? Does it show me my code is a performance issue? – kralarmerlin May 22 '21 at 12:54
  • 1
    Please read: [Profiling (computer programming) (Wikipedia)](https://en.wikipedia.org/wiki/Profiling_(computer_programming)) --- Please read: [How do I write a correct micro-benchmark in Java?](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java) – Turing85 May 22 '21 at 12:56
  • @Turing85 oh okay thanks. I thought string is a variable like an integer but I guess in java strings are objects. – kralarmerlin May 22 '21 at 12:57
  • 1
    As Andy said, certainly use an enum or static final constants instead of raw types 1 2 3. It greatly improves readability, and helps you write more error free code. – Kirit May 22 '21 at 12:58
  • 1
    @kralarmerlin everything that can be instantiated with `new ...` is an object. Even arrays. – Turing85 May 22 '21 at 13:01
  • @Kirit Okay thanks I will do it – kralarmerlin May 22 '21 at 13:05
  • @Turing85 oh i got it thanks – kralarmerlin May 22 '21 at 13:06

4 Answers4

6

If you compare strings >that< way, there is probably no performance difference.

However, that is the WRONG WAY to compare strings. The correct way is to use the equals(Object) method. For example.

  if (s.Str.equals("Upgrade")) {

Read this:


I apply the following code to my selection objects every 17 milliseconds.

The time that it will take to test two strings for equality is probably in the order of tens of NANOseconds. So ... basically ... the difference between comparing strings or integers is irrelevant.

This illustrates why premature optimization is a bad thing. You should only optimize code when you know that it is going to be worthwhile to spend your time on it; i.e. when you know there is going to be a pay-off.


So should I optimize after I write and finish all the code? Does 'not doing premature optimization' means that?

No it doesn't exactly mean that. (Well .. not to me anyway.) What it means to me is that you shouldn't optimize until:

  1. you have a working program whose performance you can measure,
  2. you have determined specific (quantifiable) performance criteria,
  3. you have a means of measuring the performance; e.g. an appropriate benchmarks involving real or realistic use-cases, and
  4. you have good a means of identifying the actual performance hotspots.

If you try to optimize before you have the above, you are likely to optimize the wrong parts of the code for the wrong reasons, and your effort (programmer time) is likely to be spent inefficiently.

In your specific case, my gut feeling is that if you followed the recommended process you would discover1 that this String vs int (vs enum) is irrelevant to your game's observable performance2.

But if you want to be more scientific than "gut feeling", you should wait until you have 1 through 4 settled, and then measure to see if the actual performance meets your criteria. Only then should you decide whether or not to optimize.


1 - My prediction assumes that your characterization of the problem is close enough to reality. That is always a risk when people try to identify performance issues "by eye" rather than by measuring.
2 - It is relevant to other things; e.g. code readability and maintainability, but I'm not going to address those in this Answer.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

The Answer by Stephen C is correct and wise. But your example code is ripe for a different solution entirely.

Enum

If you want performance, type-safety, easier-to-read code, and want to ensure valid values, use enum objects rather than mere strings or integers.

public enum Action { UPGRADE , SIEGE , RECRUIT }

You can use a switch for the various enum possible objects.

  Action action = Action.SIEGE ;
  …

  switch ( action ) 
  {
     case UPGRADE:
        doUpgradeStuff() ;
        break;
     case SIEGE:
        doSiegeStuff() ;
        break;
     case RECRUIT:
        doRecruitStuff() ;
        break;
     default:
        doDefaultStuff() ;
        break;
  }

Using enums this way will get even better in the future. See JEP 406: Pattern Matching for switch (Preview).

See Java Tutorials by Oracle on enums. And for an example, see their tutorial using enums for month, day-of-week, and text style.

See also this Question, linked to others.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

Comparing primitive numbers like Integer will be definitely faster compared to String in Java. It will give you faster performance if you are executing it every 17 milliseconds.

Navjot
  • 1,202
  • 1
  • 11
  • 24
  • OP did not mention "*primitive numbers*". From the title, I would assume OP talks about the wrapper-class `Integer`. --- In terms of `==`, all `==`-operations (except for maybe `long` and `double`) will take 1 cpu-cycle since reference-bit-size-lenght values are compared. – Turing85 May 22 '21 at 12:54
  • The second code sample from OP appears to be using primitive `int`. Assuming s.type is also `int`. – Kirit May 22 '21 at 13:01
  • We should not write speculative answer. Instead, we should ask for clarification in the comments. – Turing85 May 22 '21 at 13:02
0

Yes there is difference. String is a object and int is a primitive type. when you are doing object == "string" it is matching the address. You need to use equals method to check the exact match.