Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-7659

primopts for CompileStatic integer division

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Open
    • Minor
    • Resolution: Unresolved
    • 2.4.5
    • None
    • None

    Description

      Since operations a+b with int can be supported with primitive operations, it would be nice if division could as well. I think this is possible to do in certain circumstances and still adhere to the semantics that int / int results in BigDecimal. I believe if you have (int)(int / int), I can't think of a case where a primitive division would give a different result than with BigDecimal.

      @groovy.transform.CompileStatic
      int idiv_static(int a) {
        (int)(a / 2)
      }
      
      int idiv_dynamic(int a) {
        (int)(a / 2)
      }
      
      @groovy.transform.CompileStatic
      int iplus_static(int a) {
        a + 5
      }
      
      int iplus_dynamic(int a) {
        a + 5
      }
      

      We can see the bytecode for iplus_static generated by Groovy 2.4.5:

      ILOAD 1
      ICONST_5
      IADD
      IRETURN
      

      But for idiv_static, it converts the ints to Integer, calls a method that results in BigDecimal division and then converts that to int.

          ILOAD 1
          INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;
          ICONST_2
          INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;
          INVOKESTATIC org/codehaus/groovy/runtime/dgmimpl/NumberNumberDiv.div (Ljava/lang/Number;Ljava/lang/Number;)Ljava/lang/Number;
          INVOKESTATIC org/codehaus/groovy/runtime/typehandling/DefaultTypeTransformation.intUnbox (Ljava/lang/Object;)I
          IRETURN
      

      Attachments

        Activity

          People

            Unassigned Unassigned
            gillius Jason Winnebeck
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated: