aboutsummaryrefslogtreecommitdiffstats
path: root/lint/libs/lint_checks/src/com/android/tools/lint/checks/JavaPerformanceDetector.java
blob: e99005cc85317c7fa51216935778025ce1d98327 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.tools.lint.checks;

import com.android.tools.lint.detector.api.Category;
import com.android.tools.lint.detector.api.Context;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.JavaContext;
import com.android.tools.lint.detector.api.Scope;
import com.android.tools.lint.detector.api.Severity;
import com.android.tools.lint.detector.api.Speed;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import lombok.ast.AstVisitor;
import lombok.ast.BinaryExpression;
import lombok.ast.BinaryOperator;
import lombok.ast.ConstructorInvocation;
import lombok.ast.Expression;
import lombok.ast.ForwardingAstVisitor;
import lombok.ast.If;
import lombok.ast.MethodDeclaration;
import lombok.ast.MethodInvocation;
import lombok.ast.Node;
import lombok.ast.Select;
import lombok.ast.StrictListAccessor;
import lombok.ast.This;
import lombok.ast.Throw;
import lombok.ast.TypeReference;
import lombok.ast.TypeReferencePart;
import lombok.ast.UnaryExpression;
import lombok.ast.VariableDefinition;
import lombok.ast.VariableReference;

/**
 * Looks for performance issues in Java files, such as memory allocations during
 * drawing operations and using HashMap instead of SparseArray.
 */
public class JavaPerformanceDetector extends Detector implements Detector.JavaScanner {
    /** Allocating objects during a paint method */
    public static final Issue PAINT_ALLOC = Issue.create(
            "DrawAllocation", //$NON-NLS-1$
            "Looks for memory allocations within drawing code",

            "You should avoid allocating objects during a drawing or layout operation. These " +
            "are called frequently, so a smooth UI can be interrupted by garbage collection " +
            "pauses caused by the object allocations.\n" +
            "\n" +
            "The way this is generally handled is to allocate the needed objects up front " +
            "and to reuse them for each drawing operation.\n" +
            "\n" +
            "Some methods allocate memory on your behalf (such as Bitmap.create), and these " +
            "should be handled in the same way.",

            Category.PERFORMANCE,
            9,
            Severity.WARNING,
            JavaPerformanceDetector.class,
            Scope.JAVA_FILE_SCOPE);

    /** Using HashMaps where SparseArray would be better */
    public static final Issue USE_SPARSEARRAY = Issue.create(
            "UseSparseArrays", //$NON-NLS-1$
            "Looks for opportunities to replace HashMaps with the more efficient SparseArray",

            "For maps where the keys are of type integer, it's typically more efficient to " +
            "use the Android SparseArray API. This check identifies scenarios where you might " +
            "want to consider using SparseArray instead of HashMap for better performance.\n" +
            "\n" +
            "This is *particularly* useful when the value types are primitives like ints, " +
            "where you can use SparseIntArray and avoid auto-boxing the values from int to " +
            "Integer.\n" +
            "\n" +
            "If you need to construct a HashMap because you need to call an API outside of " +
            "your control which requires a Map, you can suppress this warning using for " +
            "example the @SuppressLint annotation.",

            Category.PERFORMANCE,
            4,
            Severity.WARNING,
            JavaPerformanceDetector.class,
            Scope.JAVA_FILE_SCOPE);

    /** Using {@code new Integer()} instead of the more efficient {@code Integer.valueOf} */
    public static final Issue USE_VALUEOF = Issue.create(
            "UseValueOf", //$NON-NLS-1$
            "Looks for usages of \"new\" for wrapper classes which should use \"valueOf\" instead",

            "You should not call the constructor for wrapper classes directly, such as" +
            "\"new Integer(42)\". Instead, call the \"valueOf\" factory method, such as " +
            "Integer.valueOf(42). This will typically use less memory because common integers " +
            "such as 0 and 1 will share a single instance.",

            Category.PERFORMANCE,
            4,
            Severity.WARNING,
            JavaPerformanceDetector.class,
            Scope.JAVA_FILE_SCOPE);

    private static final String INT = "int";                                //$NON-NLS-1$
    private static final String INTEGER = "Integer";                        //$NON-NLS-1$
    private static final String BOOL = "boolean";                           //$NON-NLS-1$
    private static final String BOOLEAN = "Boolean";                        //$NON-NLS-1$
    private static final String LONG = "Long";                              //$NON-NLS-1$
    private static final String CHARACTER = "Character";                    //$NON-NLS-1$
    private static final String DOUBLE = "Double";                          //$NON-NLS-1$
    private static final String FLOAT = "Float";                            //$NON-NLS-1$
    private static final String HASH_MAP = "HashMap";                       //$NON-NLS-1$
    private static final String CANVAS = "Canvas";                          //$NON-NLS-1$
    private static final String ON_DRAW = "onDraw";                         //$NON-NLS-1$
    private static final String ON_LAYOUT = "onLayout";                     //$NON-NLS-1$
    private static final String ON_MEASURE = "onMeasure";                   //$NON-NLS-1$
    private static final String LAYOUT = "layout";                          //$NON-NLS-1$

    /** Constructs a new {@link JavaPerformanceDetector} check */
    public JavaPerformanceDetector() {
    }

    @Override
    public boolean appliesTo(Context context, File file) {
        return true;
    }

    @Override
    public Speed getSpeed() {
        return Speed.FAST;
    }

    // ---- Implements JavaScanner ----

    @Override
    public List<Class<? extends Node>> getApplicableNodeTypes() {
        List<Class<? extends Node>> types = new ArrayList<Class<? extends Node>>(3);
        types.add(ConstructorInvocation.class);
        types.add(MethodDeclaration.class);
        types.add(MethodInvocation.class);
        return types;
    }

    @Override
    public AstVisitor createJavaVisitor(JavaContext context) {
        return new PerformanceVisitor(context);
    }

    private static class PerformanceVisitor extends ForwardingAstVisitor {
        private final JavaContext mContext;
        /** Whether allocations should be "flagged" in the current method */
        private boolean mFlagAllocations;
        private boolean mCheckMaps;
        private boolean mCheckAllocations;
        private boolean mCheckValueOf;

        public PerformanceVisitor(JavaContext context) {
            mContext = context;

            mCheckAllocations = context.isEnabled(PAINT_ALLOC);
            mCheckMaps = context.isEnabled(USE_SPARSEARRAY);
            mCheckValueOf = context.isEnabled(USE_VALUEOF);
            assert mCheckAllocations || mCheckMaps || mCheckValueOf; // enforced by infrastructure
        }

        @Override
        public boolean visitMethodDeclaration(MethodDeclaration node) {
            mFlagAllocations = isBlockedAllocationMethod(node);

            return super.visitMethodDeclaration(node);
        }

        @Override
        public boolean visitConstructorInvocation(ConstructorInvocation node) {
            String typeName = null;
            if (mCheckMaps) {
                TypeReference reference = node.astTypeReference();
                typeName = reference.astParts().last().astIdentifier().astValue();
                // TODO: Should we handle factory method constructions of HashMaps as well,
                // e.g. via Guava? This is a bit trickier since we need to infer the type
                // arguments from the calling context.
                if (typeName.equals(HASH_MAP)) {
                    checkSparseArray(node, reference);
                }
            }

            if (mCheckValueOf) {
                if (typeName == null) {
                    TypeReference reference = node.astTypeReference();
                    typeName = reference.astParts().last().astIdentifier().astValue();
                }
                if ((typeName.equals(INTEGER)
                        || typeName.equals(BOOLEAN)
                        || typeName.equals(FLOAT)
                        || typeName.equals(CHARACTER)
                        || typeName.equals(LONG)
                        || typeName.equals(DOUBLE))
                        && node.astTypeReference().astParts().size() == 1
                        && node.astArguments().size() == 1) {
                    String argument = node.astArguments().first().toString();
                    mContext.report(USE_VALUEOF, node, mContext.getLocation(node),
                            String.format("Use %1$s.valueOf(%2$s) instead", typeName, argument),
                            null);
                }
            }

            if (mFlagAllocations && !(node.getParent() instanceof Throw) && mCheckAllocations) {
                // Make sure we're still inside the method declaration that marked
                // mInDraw as true, in case we've left it and we're in a static
                // block or something:
                Node method = node;
                while (method != null) {
                    if (method instanceof MethodDeclaration) {
                        break;
                    }
                    method = method.getParent();
                }
                if (method != null && isBlockedAllocationMethod(((MethodDeclaration) method))
                        && !isLazilyInitialized(node)) {
                    reportAllocation(node);
                }
            }

            return super.visitConstructorInvocation(node);
        }

        private void reportAllocation(Node node) {
            mContext.report(PAINT_ALLOC, node, mContext.getLocation(node),
                "Avoid object allocations during draw/layout operations (preallocate and " +
                "reuse instead)", null);
        }

        @Override
        public boolean visitMethodInvocation(MethodInvocation node) {
            if (mFlagAllocations && node.astOperand() != null) {
                // Look for forbidden methods
                String methodName = node.astName().astValue();
                if (methodName.equals("createBitmap")                              //$NON-NLS-1$
                        || methodName.equals("createScaledBitmap")) {              //$NON-NLS-1$
                    String operand = node.astOperand().toString();
                    if (operand.equals("Bitmap")                                   //$NON-NLS-1$
                            || operand.equals("android.graphics.Bitmap")) {        //$NON-NLS-1$
                        if (!isLazilyInitialized(node)) {
                            reportAllocation(node);
                        }
                    }
                } else if (methodName.startsWith("decode")) {                      //$NON-NLS-1$
                    // decodeFile, decodeByteArray, ...
                    String operand = node.astOperand().toString();
                    if (operand.equals("BitmapFactory")                            //$NON-NLS-1$
                            || operand.equals("android.graphics.BitmapFactory")) { //$NON-NLS-1$
                        if (!isLazilyInitialized(node)) {
                            reportAllocation(node);
                        }
                    }
                } else if (methodName.equals("getClipBounds")) {                   //$NON-NLS-1$
                    if (node.astArguments().isEmpty()) {
                        mContext.report(PAINT_ALLOC, node, mContext.getLocation(node),
                                "Avoid object allocations during draw operations: Use " +
                                "Canvas.getClipBounds(Rect) instead of Canvas.getClipBounds() " +
                                "which allocates a temporary Rect", null);
                    }
                }
            }

            return super.visitMethodInvocation(node);
        }

        /**
         * Check whether the given invocation is done as a lazy initialization,
         * e.g. {@code if (foo == null) foo = new Foo();}.
         * <p>
         * This tries to also handle the scenario where the check is on some
         * <b>other</b> variable - e.g.
         * <pre>
         *    if (foo == null) {
         *        foo == init1();
         *        bar = new Bar();
         *    }
         * </pre>
         * or
         * <pre>
         *    if (!initialized) {
         *        initialized = true;
         *        bar = new Bar();
         *    }
         * </pre>
         */
        private boolean isLazilyInitialized(Node node) {
            Node curr = node.getParent();
            while (curr != null) {
                if (curr instanceof MethodDeclaration) {
                    return false;
                } else if (curr instanceof If) {
                    If ifNode = (If) curr;
                    // See if the if block represents a lazy initialization:
                    // compute all variable names seen in the condition
                    // (e.g. for "if (foo == null || bar != foo)" the result is "foo,bar"),
                    // and then compute all variables assigned to in the if body,
                    // and if there is an overlap, we'll consider the whole if block
                    // guarded (so lazily initialized and an allocation we won't complain
                    // about.)
                    List<String> assignments = new ArrayList<String>();
                    AssignmentTracker visitor = new AssignmentTracker(assignments);
                    ifNode.astStatement().accept(visitor);
                    if (assignments.size() > 0) {
                        List<String> references = new ArrayList<String>();
                        addReferencedVariables(references, ifNode.astCondition());
                        if (references.size() > 0) {
                            SetView<String> intersection = Sets.intersection(
                                    new HashSet<String>(assignments),
                                    new HashSet<String>(references));
                            return intersection.size() > 0;
                        }
                    }
                    return false;

                }
                curr = curr.getParent();
            }

            return false;
        }

        /** Adds any variables referenced in the given expression into the given list */
        private static void addReferencedVariables(Collection<String> variables,
                Expression expression) {
            if (expression instanceof BinaryExpression) {
                BinaryExpression binary = (BinaryExpression) expression;
                addReferencedVariables(variables, binary.astLeft());
                addReferencedVariables(variables, binary.astRight());
            } else if (expression instanceof UnaryExpression) {
                UnaryExpression unary = (UnaryExpression) expression;
                addReferencedVariables(variables, unary.astOperand());
            } else if (expression instanceof VariableReference) {
                VariableReference reference = (VariableReference) expression;
                variables.add(reference.astIdentifier().astValue());
            } else if (expression instanceof Select) {
                Select select = (Select) expression;
                if (select.astOperand() instanceof This) {
                    variables.add(select.astIdentifier().astValue());
                }
            }
        }

        /**
         * Returns whether the given method declaration represents a method
         * where allocating objects is not allowed for performance reasons
         */
        private boolean isBlockedAllocationMethod(MethodDeclaration node) {
            return isOnDrawMethod(node) || isOnMeasureMethod(node) || isOnLayoutMethod(node)
                    || isLayoutMethod(node);
        }

        /**
         * Returns true if this method looks like it's overriding android.view.View's
         * {@code protected void onDraw(Canvas canvas)}
         */
        private static boolean isOnDrawMethod(MethodDeclaration node) {
            if (ON_DRAW.equals(node.astMethodName().astValue())) {
                StrictListAccessor<VariableDefinition, MethodDeclaration> parameters =
                        node.astParameters();
                if (parameters != null && parameters.size() == 1) {
                    VariableDefinition arg0 = parameters.first();
                    TypeReferencePart type = arg0.astTypeReference().astParts().last();
                    String typeName = type.getTypeName();
                    if (typeName.equals(CANVAS)) {
                        return true;
                    }
                }
            }

            return false;
        }

        /**
         * Returns true if this method looks like it's overriding
         * android.view.View's
         * {@code protected void onLayout(boolean changed, int left, int top,
         *      int right, int bottom)}
         */
        private static boolean isOnLayoutMethod(MethodDeclaration node) {
            if (ON_LAYOUT.equals(node.astMethodName().astValue())) {
                StrictListAccessor<VariableDefinition, MethodDeclaration> parameters =
                        node.astParameters();
                if (parameters != null && parameters.size() == 5) {
                    Iterator<VariableDefinition> iterator = parameters.iterator();
                    if (!iterator.hasNext()) {
                        return false;
                    }

                    // Ensure that the argument list matches boolean, int, int, int, int
                    TypeReferencePart type = iterator.next().astTypeReference().astParts().last();
                    if (!type.getTypeName().equals(BOOL) || !iterator.hasNext()) {
                        return false;
                    }
                    for (int i = 0; i < 4; i++) {
                        type = iterator.next().astTypeReference().astParts().last();
                        if (!type.getTypeName().equals(INT)) {
                            return false;
                        }
                        if (!iterator.hasNext()) {
                            return i == 3;
                        }
                    }
                }
            }

            return false;
        }

        /**
         * Returns true if this method looks like it's overriding android.view.View's
         * {@code protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)}
         */
        private static boolean isOnMeasureMethod(MethodDeclaration node) {
            if (ON_MEASURE.equals(node.astMethodName().astValue())) {
                StrictListAccessor<VariableDefinition, MethodDeclaration> parameters =
                        node.astParameters();
                if (parameters != null && parameters.size() == 2) {
                    VariableDefinition arg0 = parameters.first();
                    VariableDefinition arg1 = parameters.last();
                    TypeReferencePart type1 = arg0.astTypeReference().astParts().last();
                    TypeReferencePart type2 = arg1.astTypeReference().astParts().last();
                    return INT.equals(type1.getTypeName()) && INT.equals(type2.getTypeName());
                }
            }

            return false;
        }

        /**
         * Returns true if this method looks like it's overriding android.view.View's
         * {@code public void layout(int l, int t, int r, int b)}
         */
        private static boolean isLayoutMethod(MethodDeclaration node) {
            if (LAYOUT.equals(node.astMethodName().astValue())) {
                StrictListAccessor<VariableDefinition, MethodDeclaration> parameters =
                        node.astParameters();
                if (parameters != null && parameters.size() == 4) {
                    Iterator<VariableDefinition> iterator = parameters.iterator();
                    for (int i = 0; i < 4; i++) {
                        if (!iterator.hasNext()) {
                            return false;
                        }
                        VariableDefinition next = iterator.next();
                        TypeReferencePart type = next.astTypeReference().astParts().last();
                        if (!INT.equals(type.getTypeName())) {
                            return false;
                        }
                    }
                    return true;
                }
            }

            return false;
        }


        /**
         * Checks whether the given constructor call and type reference refers
         * to a HashMap constructor call that is eligible for replacement by a
         * SparseArray call instead
         */
        private void checkSparseArray(ConstructorInvocation node, TypeReference reference) {
            // reference.hasTypeArguments returns false where it should not
            StrictListAccessor<TypeReference, TypeReference> types = reference.getTypeArguments();
            if (types != null && types.size() == 2) {
                TypeReference first = types.first();
                if (first.getTypeName().equals(INTEGER)) {
                    String valueType = types.last().getTypeName();
                    if (valueType.equals(INTEGER)) {
                        mContext.report(USE_SPARSEARRAY, node, mContext.getLocation(node),
                            "Use new SparseIntArray(...) instead for better performance",
                            null);
                    } else if (valueType.equals(BOOLEAN)) {
                        mContext.report(USE_SPARSEARRAY, node, mContext.getLocation(node),
                                "Use new SparseBooleanArray(...) instead for better performance",
                                null);
                    } else if (valueType.equals(LONG) && mContext.getProject().getMinSdk() >= 17) {
                        mContext.report(USE_SPARSEARRAY, node, mContext.getLocation(node),
                                "Use new SparseLongArray(...) instead for better performance",
                                null);
                    } else {
                        mContext.report(USE_SPARSEARRAY, node, mContext.getLocation(node),
                            String.format(
                                "Use new SparseArray<%1$s>(...) instead for better performance",
                              valueType),
                            null);
                    }
                }
            }
        }
    }

    /** Visitor which records variable names assigned into */
    private static class AssignmentTracker extends ForwardingAstVisitor {
        private final Collection<String> mVariables;

        public AssignmentTracker(Collection<String> variables) {
            mVariables = variables;
        }

        @Override
        public boolean visitBinaryExpression(BinaryExpression node) {
            BinaryOperator operator = node.astOperator();
            if (operator == BinaryOperator.ASSIGN || operator == BinaryOperator.OR_ASSIGN) {
                Expression left = node.astLeft();
                String variable;
                if (left instanceof Select && ((Select) left).astOperand() instanceof This) {
                    variable = ((Select) left).astIdentifier().astValue();
                } else {
                    variable = left.toString();
                }
                mVariables.add(variable);
            }

            return super.visitBinaryExpression(node);
        }
    }
}