提高Java代码效率

Ste*_*son 0 java performance android

以下代码运行~550ms,用户正在等待这种情况不断发生(除了来自外部库的一些额外处理).有没有办法改进从int(像素)数组到最终Bitmap的转换?

int[] pixels   = imageDecoder.nativeGetImgBytes();  // a big tiff image

Bitmap b = Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888);

ByteArrayOutputStream out = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 70, out);

byte[] byteArray = out.toByteArray();
b = BitmapFactory.decodeByteArray(byteArray, 0, array.length);

return b;
Run Code Online (Sandbox Code Playgroud)

Com*_*are 5

之后,我将像素int []数组并创建一个jpeg压缩的Bitmap,最终获取并在其他类的屏幕上显示.

不,你不是.A Bitmap未压缩.可以压缩位图文件,但不能压缩Bitmap.

因此,将代码替换为:

int[] pixels   = imageDecoder.nativeGetImgBytes();  // a big tiff image

return Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888);
Run Code Online (Sandbox Code Playgroud)

除了浪费的编码和解码JPEG的CPU时间之外,您现有的代码浪费了大量的堆空间.最终会有两个完整的Bitmap实例和许多堆分配,因为ByteArrayOutputStream它从最初的大小缓慢扩展到最终的大小.