【原创】java.io.InputStream优化
今天无聊看java源码时发现java.io.InputStream类用于移动文件指针的skip()方法可以再优化一下:
源码:
public long skip(long n) throws IOException { long remaining = n; int nr; if (skipBuffer == null) skipBuffer = new byte[SKIP_BUFFER_SIZE]; byte[] localSkipBuffer = skipBuffer; if (n <= 0) { return 0; } while (remaining > 0) { nr = read(localSkipBuffer, 0, (int) Math.min(SKIP_BUFFER_SIZE, remaining)); if (nr < 0) { break; } remaining -= nr; } return n - remaining; }
可以优化为:
public long skip(long n) throws IOException { if (n <= 0) { return 0; } int i=0; while ( read() != -1 && i < n) { i++; } return i; }
这样即节省了skipBuffer2048个空间,代码也更简单;
继续看了一下子类的代码,都覆盖了这个方法。但优化后的方法总比优化前强!
相关推荐
dabian 2020-09-07
zhoutaifeng 2020-01-30
windsky 2014-03-19
toperfect 2014-07-14
bentocaffe 2018-10-31
tycoon 2018-08-13
拉斯厄尔高福 2013-09-16
xiaqiuling 2018-01-29
waterstarsx 2017-05-19
PHP100 2019-03-28
PHP100 2019-03-27
优主张 2018-01-04