Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 努力编写高效的代码_Java_If Statement - Fatal编程技术网

Java 努力编写高效的代码

Java 努力编写高效的代码,java,if-statement,Java,If Statement,我正在为一个大型应用程序编写代码,有一个事件需要进行大量的if/else检查 例如: if (i == 1) { /* some logic */ } else if (i == 2) { /* some logic */ } // ... // ... else if (i == 1000) { /* some logic */ } 有没有更有效或更有条理的方法来写这篇文章?使用switch语句。 前 或者,如果您知道最常见的情况,您可以将其分解,以改进算法运行时间,这可能需要不同的方法。如

我正在为一个大型应用程序编写代码,有一个事件需要进行大量的
if
/
else
检查

例如:

if (i == 1) { /* some logic */ }
else if (i == 2) { /* some logic */ }
// ...
// ...
else if (i == 1000) { /* some logic */ }
有没有更有效或更有条理的方法来写这篇文章?

使用switch语句。 前


或者,如果您知道最常见的情况,您可以将其分解,以改进算法运行时间,这可能需要不同的方法。

如果您在这些代码块中执行1000个不同的操作,那么问题在于逻辑复杂性。在这种情况下,您别无选择,只能这样编码或更改为
开关。
对于
if
,唯一需要记住的关键是将您知道的最有可能/最频繁的情况移至顶部

如果你不做1000种不同的事情,必须是<强>单独编码< /强>,那么你可以考虑其中的一些选项:

  • 如果可能的话,将其细分为几个范围:

    if(i < 300): {
        //do something
    } else if(i < 600) {
        // do another thing
    } 
    //do the default thing
    

  • 然后,您可以根据可以分组的任何逻辑编写一些实现。

    听起来您有一个函数集合,只需要使用
    HashMap
    i
    将是地图的索引。Hashmaps非常有用,因为它们可以快速找到键的对应值,而无需在找到匹配项之前比较大量值

    下面是一个从
    Any
    Any=>Any
    HashMap
    示例。因为Scala支持元组,所以这是一个完全通用的解决方案

    object Hello extends App {
      import scala.collection.immutable
    
      type F1 = (Any) => Any
    
      val hashMap: immutable.Map[Int, F1] =
        immutable.HashMap[Int, F1](
          1    -> { (a: Int)               => a * 2               }.asInstanceOf[F1], // Function literal that doubles it's input
          2    -> { (tuple: (String, Int)) => tuple._1 * tuple._2 }.asInstanceOf[F1], // Function literal that repeats the string
          1000 -> { (_: Unit)              => s"The date and time is ${ new java.util.Date() }" }.asInstanceOf[F1]
        )
    
      def lookup(i: Int, args: Any): Any = hashMap(i)(args)
    
      def report(i: Int, args: Any): Unit = println(s"$i: ${ lookup(i, args) }")
    
      report(1, 21)
      report(2, ("word ", 5))
      report(1000, ())
    }
    
    以下是输出:

    1: 42
    2: word word word word word 
    1000: The date and time is Sat Dec 23 19:45:56 PST 2017
    
    更新:这是一个使用数组的版本。请注意,对于此版本,索引必须从0开始,而不是以前的任意数字:

    object Hello2 extends App {
      type F1 = (Any) => Any
    
      val array: Array[F1] =
        Array[F1](
          { (a: Int)               => a * 2               }.asInstanceOf[F1], // Function literal that doubles it's input
          { (tuple: (String, Int)) => tuple._1 * tuple._2 }.asInstanceOf[F1], // Function literal that repeats the string
          { (_: Unit)              => s"The date and time is ${ new java.util.Date() }" }.asInstanceOf[F1]
        )
    
      def lookup(i: Int, args: Any): Any = array(i)(args)
    
      def report(i: Int, args: Any): Unit = println(s"$i: ${ lookup(i, args) }")
    
      report(0, 21)
      report(1, ("word ", 5))
      report(2, ())
    }
    
    输出为:

    0: 42
    1: word word word word word 
    2: The date and time is Sat Dec 23 20:32:33 PST 2017
    

    对它被称为
    switch
    语句。java switch语句编译成一个高效的查找。您衡量过它是否低效吗?不要假设-测试!不,问题不会一直存在
    switch
    语句有1000个大小写,不能编译成
    if-else
    链。@KenWhite不,它们“基本上做的事情都不一样”。找一段时间看看目标代码。你不必知道在
    switch
    语句中哪一个是最常见的,也不必将这些情况移到最上面。如果数字是连续的,数组将比哈希映射更有效,因为它将消除哈希计算(无论对于整数来说多么便宜)并确保不会因为表大小的错误选择而导致冲突。是的,但OP没有说明可以假设的情况。他说了,集合1,2,…,1000通常被称为整数集合1-1000。数组大小可以简单地调整为使用任何固定的起始数,不仅仅是零:给定数字
    i
    和起始偏移量
    s
    ,索引就是
    i-s
    。我花了一秒钟才意识到您是在用Scala编写的(我对此一无所知),因为OP标记了Java+1不管怎样。
    object Hello2 extends App {
      type F1 = (Any) => Any
    
      val array: Array[F1] =
        Array[F1](
          { (a: Int)               => a * 2               }.asInstanceOf[F1], // Function literal that doubles it's input
          { (tuple: (String, Int)) => tuple._1 * tuple._2 }.asInstanceOf[F1], // Function literal that repeats the string
          { (_: Unit)              => s"The date and time is ${ new java.util.Date() }" }.asInstanceOf[F1]
        )
    
      def lookup(i: Int, args: Any): Any = array(i)(args)
    
      def report(i: Int, args: Any): Unit = println(s"$i: ${ lookup(i, args) }")
    
      report(0, 21)
      report(1, ("word ", 5))
      report(2, ())
    }
    
    0: 42
    1: word word word word word 
    2: The date and time is Sat Dec 23 20:32:33 PST 2017