Avoid object allocations during draw/layout operations

1765 단어
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint = new Paint(Paint.LINEAR_TEXT_FLAG);
    }

사용자 정의 View의 onDraw에 new 객체가 있으면 다음과 같은 경고가 표시됩니다.
Avoid object allocations during draw/layout operations (preallocate and reuse instead)

Issue: Looks for memory allocations within drawing code
Id: DrawAllocation

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.

The way this is generally handled is to allocate the needed objects up front and to reuse them for each drawing operation.
Some methods allocate memory on your behalf (such as Bitmap.create), and these should be handled in the same way.

번역의 뜻은draw/layout(onDraw() 반복 운행)이라는 빈번한 작업에서 대상을 분배해야 하기 때문에 대량의 새로운 대상을 초래하고 빈번한 쓰레기 회수를 초래할 수 있다.해결 방법은 new 대상을 구조 함수에 놓고 onDraw에서 복원하는 것입니다.
class YourClass extends View
{
    //Paint paint = new Paint(); 
    Paint paint;

    public YourClass(Context context) {
        this(context, null);
        init();
    }

    public YourClass(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        init();
    }

    public YourClass(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init()
    {
      paint = new Paint(Paint.LINEAR_TEXT_FLAG);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setColor(Color.WHITE);


stackoverflow

  • Object allocation during draw/layout?

  • 좋은 웹페이지 즐겨찾기