Menu

#377 UseArraysAsListInsteadOfTightLoops

closed
None
5
2012-10-07
2005-11-30
No

When we have to pass between "Object arrays" and List
we should use the utility classe Arrays.

This should give us two advanatges:

  • less code
  • (slightly better) performance
    [in the JDK implementation the array becomes the "inner
    data structure" of the List implementation that is
    returned.. no copy]

-- before
List arrList = new ArrayList();

for (int i=0;i< MAX; i++) {
arrList.add(arr[i]);
}

-- after
List arrList = Arrays.asList(arr);

I might try writing this rule with an xpath expression..

Discussion

  • Fabio Insaccanebbia

    Logged In: YES
    user_id=762447

    OK, not easy :-(

    //Statement[(ForStatement) and (count(.//IfStatement)
    =0)]
    //StatementExpression
    [PrimaryExpression/PrimaryPrefix/Name
    [@Image = concat
    (ancestor::MethodDeclaration//LocalVariableDeclaration
    [./Type//ClassOrInterfaceType[@Image = 'List' or @Image
    = 'ArrayList']]/VariableDeclarator/VariableDeclaratorId
    [count(..//AllocationExpression/ClassOrInterfaceType
    [@Image="ArrayList"])=1]/@Image,".add")]
    and
    PrimaryExpression/PrimarySuffix/Arguments/ArgumentList/Expre
    ssion/
    PrimaryExpression/PrimaryPrefix/Name
    [@Image =
    ancestor::MethodDeclaration//LocalVariableDeclaration
    [@Array="true"]/VariableDeclarator/VariableDeclaratorId/@Ima
    ge]
    /../..[count(.//PrimarySuffix)
    =1]/PrimarySuffix/Expression/PrimaryExpression/PrimaryPrefix
    /Name
    ]

    The XML rule

    <rule name="UseArraysAsList" message="Use asList instead of tight loops" class="">
    <description>
    The class java.util.Arrays has a "asList" method that
    should be use when you want to create a new List from
    an array of objects. It is faster than executing a loop to
    cpy all the elements of the array one by one
    </description>
    <properties>
    <property name="xpath">
    <value></value></property></properties></rule>

    </value>
    </property>
    


    <priority>3</priority>
    <example></example>


     
  • Tom Copeland

    Tom Copeland - 2005-12-08

    Logged In: YES
    user_id=5159

    Moving to 'patches', thanks Fabio!

    tom

     
  • Tom Copeland

    Tom Copeland - 2005-12-14

    Logged In: YES
    user_id=5159

    Committed to CVS, and you can download a new pmd-3.4.jar
    file here:

    http://infoether.com/~tom/pmd-3.4.jar

    that contains this rule in the optimizations ruleset.

    Thanks Fabio!

    Yours,

    Tom
    Using PMD? Get the book, "PMD Applied"! http://pmdapplied.com/

     

Log in to post a comment.

MongoDB Logo MongoDB