性能优化(1.4)-各种布局的性能对比(LinearLayout,RelativeLayout)

主目录见:Android高级进阶知识(这是总目录索引)
 前面一周由于休假所以没有写文章,今天刚回来呢,打算给大家一起说说这两个布局的性能对比,通过这个性能对比我们也能更好地使用这两个布局,希望大家一起享受这一段旅程。
同时推荐一篇ConstraintLayout 完全解析 快来优化你的布局吧,这个是新的layout,大家可以看看。

一.目标

今天主要是通过源码来分析下这两个布局的性能,但是不会非常详细地一句一句代码进行解析,不然代码涉及的东西还蛮多,如果需要每个都懂得话可以留言我会说明。
1.弄懂LinearLayout和RelativeLayout的性能;
2.明白在什么场景使用什么布局。

二.性能对比

我们这里先说下我个人看法,在简单布局可以用单层LinearLayout完成的布局我们可以选择LinearLayout进行布局,如果用单层LinearLayout完成不了而要嵌套的话,那么我们可以考虑用RelativeLayout来完成布局。

1.绘制流程

 通过前面View和ViewGroup的绘制原理源码分析这篇文章我们知道了我们的绘制过程是从performTraversals()分别调用perfromMeasure、performLayout和performDraw这三个方法。这三个方法分别完成顶级View的measure、layout和draw三大流程。然后遍历子节点分别重复这几个步骤,直到整个view树完成,view也就显示出来。所以我们看下这几个流程的耗时我们就知道他们的性能情况了。
 首先我们选择了一个一样的布局,然后分别用RelativeLayout布局和LinearLayout布局,我们看下布局的样子:

性能优化(1.4)-各种布局的性能对比(LinearLayout,RelativeLayout)_第1张图片
布局

然后我们看下顶层分别用LinearLayout和用RelativeLayout的耗时情况:


性能优化(1.4)-各种布局的性能对比(LinearLayout,RelativeLayout)_第2张图片
RelativeLayout
性能优化(1.4)-各种布局的性能对比(LinearLayout,RelativeLayout)_第3张图片
LinearLayout

上面两张图是用Hierarchy Viewer里面看的,如果有兴趣也可以自己去看看。我们看到这里的layout和draw这两个流程时间差不多,当然由于这个工具有可能多次刷新会出现结果不同,但是不同的是measure这个流程RelativeLayout用时都会相对长些,因为这里布局简单不涉及多层嵌套,所以RelativeLayout不能发挥出优势,我们来看看源码是为什么?

2.LinearLayout

我们今天就来看看measure这个流程这两个布局分别干了什么:

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mOrientation == VERTICAL) {
            measureVertical(widthMeasureSpec, heightMeasureSpec);
        } else {
            measureHorizontal(widthMeasureSpec, heightMeasureSpec);
        }
    }

我们看到代码很简单,就是根据orientation是垂直的还是水平的进行布局。我们就来看看 measureHorizontal的源码:

        // See how wide everyone is. Also remember max height.
//获得子view的宽度,并记下最大的高度
        for (int i = 0; i < count; ++i) {
            final View child = getVirtualChildAt(i);
            if (child == null) {
                mTotalLength += measureNullChild(i);//默认返回0
                continue;
            }
           
            if (child.getVisibility() == GONE) {
                i += getChildrenSkipCount(child, i);//默认返回0
                continue;
            }

            if (hasDividerBeforeChildAt(i)) {
                mTotalLength += mDividerWidth;
            }

            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
//获取所有子视图的lp,然后获取总共的权重weight
            totalWeight += lp.weight;

            final boolean useExcessSpace = lp.width == 0 && lp.weight > 0;
            if (widthMode == MeasureSpec.EXACTLY && useExcessSpace) {
                // Optimization: don't bother measuring children who are only
                // laid out using excess space. These views will get measured
                // later if we have space to distribute.
 //如果LinearLayout宽度是已经确定的。并且这个子view的width=0,weight>0,  
 //则mTotalLength只需要加上margin即可,  
//由于是weight>0;该view的具体高度等会还要计算  
                if (isExactly) {
                    mTotalLength += lp.leftMargin + lp.rightMargin;
                } else {
                    final int totalLength = mTotalLength;
                    mTotalLength = Math.max(totalLength, totalLength +
                            lp.leftMargin + lp.rightMargin);
                }

                // Baseline alignment requires to measure widgets to obtain the
                // baseline offset (in particular for TextViews). The following
                // defeats the optimization mentioned above. Allow the child to
                // use as much space as it wants because we can shrink things
                // later (and re-measure).
                if (baselineAligned) {
                    final int freeWidthSpec = MeasureSpec.makeSafeMeasureSpec(
                            MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.UNSPECIFIED);
                    final int freeHeightSpec = MeasureSpec.makeSafeMeasureSpec(
                            MeasureSpec.getSize(heightMeasureSpec), MeasureSpec.UNSPECIFIED);
                    child.measure(freeWidthSpec, freeHeightSpec);
                } else {
                    skippedMeasure = true;
                }
            } else {
//否则如果模式是wrap_cotent的话,那么就要先测量子view,然后将子view的宽高和间隔统计相加用
//mTotalLength 存储起来
                if (useExcessSpace) {
                    // The widthMode is either UNSPECIFIED or AT_MOST, and
                    // this child is only laid out using excess space. Measure
                    // using WRAP_CONTENT so that we can find out the view's
                    // optimal width. We'll restore the original width of 0
                    // after measurement.
                    lp.width = LayoutParams.WRAP_CONTENT;
                }

                // Determine how big this child would like to be. If this or
                // previous children have given a weight, then we allow it to
                // use all available space (and we will shrink things later
                // if needed).
                final int usedWidth = totalWeight == 0 ? mTotalLength : 0;
                measureChildBeforeLayout(child, i, widthMeasureSpec, usedWidth,
                        heightMeasureSpec, 0);

                final int childWidth = child.getMeasuredWidth();
                if (useExcessSpace) {
                    // Restore the original width and record how much space
                    // we've allocated to excess-only children so that we can
                    // match the behavior of EXACTLY measurement.
                    lp.width = 0;
                    usedExcessSpace += childWidth;
                }

                if (isExactly) {
                    mTotalLength += childWidth + lp.leftMargin + lp.rightMargin
                            + getNextLocationOffset(child);
                } else {
                    final int totalLength = mTotalLength;
                    mTotalLength = Math.max(totalLength, totalLength + childWidth + lp.leftMargin
                            + lp.rightMargin + getNextLocationOffset(child));
                }

                if (useLargestChild) {
                    largestChildWidth = Math.max(childWidth, largestChildWidth);
                }
            }
.........   
        }

我们看到LiearLayout的onMeasure中,使用了mTotalLength来保存测量过的子视图的总宽度。在for循环中,如果是wrap_content的话,那么我们会调用measureChildBeforeLayout()方法,其中一个参数是widthMeasureSpec,另外一个是usedWidth(已经被子视图使用的宽度)。每次for循环对child测量完毕后,程序就会调用getMeasuredWidth()方法来得到child的宽度,然后添加进mTotalLength 中来。这里面暂时没有考虑weight>0的情况,因为如果考虑这个的话,后面会进行第二次的测量,父视图会把剩余的宽度按照weight值的大小平均分配给相应的子视图。那么我们来看weight>0的情况,这里的代码也比较长,我们这里说明一下代码逻辑:

1.weight>0,且width=0,mode=EXACTLY,那么宽度就是share = (int) (childWeight * remainingExcess / remainingWeightSum),是根据剩余空间跟view的weight计算得到,也就是说如果剩余空间为零,那么视图的大小也会为零。
2.weight>0,mode != EXACTLY,那么得到的宽度就是本身的控件宽度加上share 的宽度。也就是说是wrap_content的话那么宽度是自身的宽度加上剩余的空间占比(也就是说能优先获得自身的布局宽度,然后再去加上剩余的空间占比)。

所以我们有结论得出,如果我们布局中设置了weight的话,那么LinearLayout的话会测量两次,这样明显影响了性能,所以我们应该能不适用weight的时候就少用。

3.RelativeLayout

RelativeLayout的源代码还是比较复杂的,而且里面的依赖关系是用图来做的,而且里面会进行图的拓扑排序。我们这里同样就不进行一句一句地讲解,我们先来手下RelativeLayout的测量做了哪些工作:

  • 1.子视图根据横向关系和纵向关系排序 sortChildren();
  • 2.初始化一些变量值;
  • 3.遍历水平关系的View,将相对布局的关系转化为左右坐标,然后确立水平方向的子View位置;
  • 4.遍历垂直关系的View,将相对布局关系转化为垂直坐标,然后确立垂直方向的子View的位置;
  • 5.baseline计算;
  • 6.宽度和高度修正。
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mDirtyHierarchy) {
            mDirtyHierarchy = false;
            sortChildren();
        }
//省略初始化变量代码
.........
        View[] views = mSortedHorizontalChildren;
        int count = views.length;

        for (int i = 0; i < count; i++) {
            View child = views[i];
            if (child.getVisibility() != GONE) {
                LayoutParams params = (LayoutParams) child.getLayoutParams();
                int[] rules = params.getRules(layoutDirection);

                applyHorizontalSizeRules(params, myWidth, rules);
                measureChildHorizontal(child, params, myWidth, myHeight);

                if (positionChildHorizontal(child, params, myWidth, isWrapContentWidth)) {
                    offsetHorizontalAxis = true;
                }
            }
        }

        views = mSortedVerticalChildren;
        count = views.length;
        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;

        for (int i = 0; i < count; i++) {
            final View child = views[i];
            if (child.getVisibility() != GONE) {
                final LayoutParams params = (LayoutParams) child.getLayoutParams();

                applyVerticalSizeRules(params, myHeight, child.getBaseline());
                measureChild(child, params, myWidth, myHeight);
                if (positionChildVertical(child, params, myHeight, isWrapContentHeight)) {
                    offsetVerticalAxis = true;
                }

                if (isWrapContentWidth) {
                    if (isLayoutRtl()) {
                        if (targetSdkVersion < Build.VERSION_CODES.KITKAT) {
                            width = Math.max(width, myWidth - params.mLeft);
                        } else {
                            width = Math.max(width, myWidth - params.mLeft - params.leftMargin);
                        }
                    } else {
                        if (targetSdkVersion < Build.VERSION_CODES.KITKAT) {
                            width = Math.max(width, params.mRight);
                        } else {
                            width = Math.max(width, params.mRight + params.rightMargin);
                        }
                    }
                }

                if (isWrapContentHeight) {
                    if (targetSdkVersion < Build.VERSION_CODES.KITKAT) {
                        height = Math.max(height, params.mBottom);
                    } else {
                        height = Math.max(height, params.mBottom + params.bottomMargin);
                    }
                }

                if (child != ignore || verticalGravity) {
                    left = Math.min(left, params.mLeft - params.leftMargin);
                    top = Math.min(top, params.mTop - params.topMargin);
                }

                if (child != ignore || horizontalGravity) {
                    right = Math.max(right, params.mRight + params.rightMargin);
                    bottom = Math.max(bottom, params.mBottom + params.bottomMargin);
                }
            }
        }
//省略宽度和高度修正代码和baseline计算代码
........
        setMeasuredDimension(width, height);
    }

从源码里面我们可以看出来,这边两次for循环分别会根据我们设置的依赖关系,比如A垂直依赖B,B水平依赖C,那么程序会进行水平方向的依赖关系解析,然后确定坐标和位置。同样垂直方向也是如此。这里的依赖关系节点是用图的形式存储,这里的代码跟Behavior里面的源码有点像,那个依赖关系也是用图来存储的,然后搜索的时候可以深度和广度搜索排序。有兴趣大家可以了解一下数据结构中图的相关知识。所以我们看到我们的RelativeLayout会进行两次的测量,这样有可能会成为性能消耗的原因,但是同时RelativeLayout在复杂布局时候有可能减少嵌套层数。所以在复杂嵌套时候我们可以考虑使用他或者LinearLayout使用到weight的情况我们也可以考虑使用它。

总结:我们上面的解释也说的很清楚了,如果有什么疑问或者错误大家可以留言哈,同时附上大家一直说的一个问题:为什么Google给开发者默认新建了个RelativeLayout,而自己却在DecorView中用了个LinearLayout?因为DecorView的层级深度已知且固定的,上面一个标题栏,下面一个内容栏,采用RelativeLayout并不会降低层级深度,因此这种情况下使用LinearLayout效率更高。

你可能感兴趣的:(性能优化(1.4)-各种布局的性能对比(LinearLayout,RelativeLayout))