简体   繁体   English

integer 和字符串比较在优化上有什么区别吗?

[英]Is there any difference in optimization between integer and string comparison?

I'm trying to make a game and I have a Selection class that holds a string named str in it.我正在尝试制作游戏,并且我有一个选择 class ,其中包含一个名为 str 的字符串。 I apply the following code to my selection objects every 17 milliseconds.我每 17 毫秒将以下代码应用于我的选择对象。

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.我在其他地方使用 str 变量。 my question is that:我的问题是:
Would it be more optimized if I assign the types to an integer when I first create the objects?如果我在第一次创建对象时将类型分配给 integer 会更优化吗?

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?这将使我编写额外的代码行(因为我必须在第一次创建时按类型分隔对象)并使代码更难以理解,但是比较整数而不是比较字符串之间会有区别吗?

If you compare strings >that< way, there is probably no performance difference.如果您以 >that< 方式比较字符串,则可能没有性能差异。

However, that is the WRONG WAY to compare strings.但是,这是比较字符串的错误方法。 The correct way is to use the equals(Object) method.正确的方法是使用equals(Object)方法。 For example.例如。

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

Read this:读这个:


I apply the following code to my selection objects every 17 milliseconds.我每 17 毫秒将以下代码应用于我的选择对象。

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;只有当你知道花时间在它上面是值得的时,你才应该优化代码; ie 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;您有衡量绩效的方法; eg 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 discover 1 that this String vs int (vs enum ) is irrelevant to your game's observable performance 2 .在您的具体情况下,我的直觉是,如果您遵循推荐的流程,您会发现1这个String vs int (vs enum ) 与您游戏的可观察性能2无关。

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.但是如果你想比“直觉”更科学,你应该等到1到4都解决了,然后测量,看看实际表现是否符合你的标准。 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. 1 - 我的预测假设您对问题的描述与现实足够接近。 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; 2 - 与其他事物有关; eg code readability and maintainability, but I'm not going to address those in this Answer.例如代码可读性和可维护性,但我不会在这个答案中解决这些问题。

The Answer by Stephen C is correct and wise. Stephen C 的回答是正确和明智的。 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) .请参阅JEP 406:开关的模式匹配(预览版)

See Java Tutorials by Oracle on enums.请参阅 Oracle 关于枚举的Java 教程 And for an example, see their tutorial using enums for month, day-of-week, and text style .例如,请参阅他们的 教程,使用 enums for month、day-of-week 和 text style

See also this Question , linked to others.另请参阅此问题,链接到其他人。

Comparing primitive numbers like Integer will be definitely faster compared to String in Java.与 Java 中的字符串相比,比较像 Integer 这样的原始数字肯定会更快。 It will give you faster performance if you are executing it every 17 milliseconds.如果您每 17 毫秒执行一次,它将为您提供更快的性能。

Yes there is difference.是的,有区别。 String is a object and int is a primitive type. String 是 object 而 int 是原始类型。 when you are doing object == "string" it is matching the address.当您执行 object == "string" 时,它与地址匹配。 You need to use equals method to check the exact match.您需要使用 equals 方法来检查完全匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM