好的,所以在花了两天时间试图找出问题并阅读了大量文章之后,我终于决定鼓起勇气寻求一些建议(我第一次来这里)。
现在到手头的问题 - 我正在编写一个程序,它将解析游戏中的 api 数据,即战斗日志。数据库中会有很多条目(20+ 百万),因此每个战斗日志页面的解析速度非常重要。
要解析的页面如下所示:http://api.erepublik.com/v1/feeds/battle_logs/10000/0。 (如果使用 chrome,请参阅源代码,它不会正确显示页面)。它有 1000 个命中条目,然后是一些战斗信息(最后一页显然会小于 1000)。平均而言,一个页面包含 175000 个字符,UTF-8 编码,xml 格式(v 1.0)。程序将在一台好的 PC 上本地运行,内存几乎是无限的(因此创建 byte[250000] 是完全可以的)。
格式从不改变,非常方便。
现在,我像往常一样开始:
//global vars,class declaration skipped
public WebObject(String url_string, int connection_timeout, int read_timeout, boolean redirects_allowed, String user_agent)
throws java.net.MalformedURLException, java.io.IOException {
// Open a URL connection
java.net.URL url = new java.net.URL(url_string);
java.net.URLConnection uconn = url.openConnection();
if (!(uconn instanceof java.net.HttpURLConnection)) {
throw new java.lang.IllegalArgumentException("URL protocol must be HTTP");
}
conn = (java.net.HttpURLConnection) uconn;
conn.setConnectTimeout(connection_timeout);
conn.setReadTimeout(read_timeout);
conn.setInstanceFollowRedirects(redirects_allowed);
conn.setRequestProperty("User-agent", user_agent);
}
public void executeConnection() throws IOException {
try {
is = conn.getInputStream(); //global var
l = conn.getContentLength(); //global var
} catch (Exception e) {
//handling code skipped
}
}
//getContentStream and getLength methods which just return'is' and 'l' are skipped
这是有趣的部分开始的地方。我运行了一些分析(使用 System.currentTimeMillis())来找出什么需要很长时间,什么不需要。对该方法的调用平均只需要 200 毫秒
public InputStream getWebPageAsStream(int battle_id, int page) throws Exception {
String url = "http://api.erepublik.com/v1/feeds/battle_logs/" + battle_id + "/" + page;
WebObject wobj = new WebObject(url, 10000, 10000, true, "Mozilla/5.0 "
+ "(Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)");
wobj.executeConnection();
l = wobj.getContentLength(); // global variable
return wobj.getContentStream(); //returns 'is' stream
}
网络操作预计需要 200 毫秒,我对此很好。但是,当我以任何方式解析 inputStream(将其读入字符串/使用 java XML 解析器/将其读入另一个 ByteArrayStream)时,该过程需要超过 1000 毫秒!
例如,如果我将上面从 getContentStream() 获得的流 ('is') 直接传递给此方法,则此代码需要 1000 毫秒:
public static Document convertToXML(InputStream is) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
doc.getDocumentElement().normalize();
return doc;
}
如果传入初始 InputStream 'is',此代码也需要大约 920 毫秒(不要读入代码本身 - 它只是通过直接计算字符来提取我需要的数据,这可以通过严格的 api 提要格式来完成) :
public static parsedBattlePage convertBattleToXMLWithoutDOM(InputStream is) throws IOException {
// Point A
BufferedReader br = new BufferedReader(new InputStreamReader(is));
LinkedList ll = new LinkedList();
String str = br.readLine();
while (str != null) {
ll.add(str);
str = br.readLine();
}
if (((String) ll.get(1)).indexOf("error") != -1) {
return new parsedBattlePage(null, null, true, -1);
}
//Point B
Iterator it = ll.iterator();
it.next();
it.next();
it.next();
it.next();
String[][] hits_arr = new String[1000][4];
String t_str = (String) it.next();
String tmp = null;
int j = 0;
for (int i = 0; t_str.indexOf("time") != -1; i++) {
hits_arr[i][0] = t_str.substring(12, t_str.length() - 11);
tmp = (String) it.next();
hits_arr[i][1] = tmp.substring(14, tmp.length() - 9);
tmp = (String) it.next();
hits_arr[i][2] = tmp.substring(15, tmp.length() - 10);
tmp = (String) it.next();
hits_arr[i][3] = tmp.substring(18, tmp.length() - 13);
it.next();
it.next();
t_str = (String) it.next();
j++;
}
String[] b_info_arr = new String[9];
int[] space_nums = {13, 10, 13, 11, 11, 12, 5, 10, 13};
for (int i = 0; i < space_nums.length; i++) {
tmp = (String) it.next();
b_info_arr[i] = tmp.substring(space_nums[i] + 4, tmp.length() - space_nums[i] - 1);
}
//Point C
return new parsedBattlePage(hits_arr, b_info_arr, false, j);
}
我尝试将默认的 BufferedReader 替换为
BufferedReader br = new BufferedReader(new InputStreamReader(is), 250000);
这并没有太大变化。我的第二次尝试是将 A 和 B 之间的代码替换为: Iterator it = IOUtils.lineIterator(is, "UTF-8");
相同的结果,除了这次 AB 是 0 毫秒,而 BC 是 1000 毫秒,所以每次调用 it.next() 都必须花费大量时间。(IOUtils 来自 apache-commons-io 库)。
这是罪魁祸首 - 将流解析为字符串所花费的时间,无论是迭代器还是 BufferedReader 在所有情况下都是大约 1000 毫秒,而其余代码花费了 0 毫秒(例如不相关)。这意味着由于某种原因将流解析为 LinkedList 或对其进行迭代会占用我的大量系统资源。问题是——为什么?难道只是java的制作方式......不......那只是愚蠢,所以我做了另一个实验。
在我的主要方法中,我在 getWebPageAsStream() 之后添加:
//Point A
ba = new byte[l]; // 'l' comes from wobj.getContentLength above
bytesRead = is.read(ba); //'is' is our URLConnection original InputStream
offset = bytesRead;
while (bytesRead != -1) {
bytesRead = is.read(ba, offset - 1, l - offset);
offset += bytesRead;
}
//Point B
InputStream is2 = new ByteArrayInputStream(ba);
//Now just working with 'is2' - the "copied" stream
InputStream->byte[] 转换再次花费了 1000 毫秒 - 这是许多人建议读取 InputStream 的方式,但它仍然很慢。猜猜看——上面的 2 个解析器方法(convertToXML() 和 convertBattlePagetoXMLWithoutDOM(),当传递 'is2' 而不是 'is' 时,在所有 4 种情况下,都在 50 毫秒内完成。
我读了一个建议,即流在解除阻塞之前等待连接关闭,所以我尝试使用 HttpComponentsClient 4.0 ( http://hc.apache.org/httpcomponents-client/index.html ),但最初的 InputStream 花了同样长的时间解析。例如这段代码:
public InputStream getWebPageAsStream2(int battle_id, int page) throws Exception {
String url = "http://api.erepublik.com/v1/feeds/battle_logs/" + battle_id + "/" + page;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpParams p = new BasicHttpParams();
HttpConnectionParams.setSocketBufferSize(p, 250000);
HttpConnectionParams.setStaleCheckingEnabled(p, false);
HttpConnectionParams.setConnectionTimeout(p, 5000);
httpget.setParams(p);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
l = (int) entity.getContentLength();
return entity.getContent();
}
处理时间更长(仅网络需要 50 毫秒)并且流解析时间保持不变。显然它可以被实例化,以免每次都创建 HttpClient 和属性(更快的网络时间),但流问题不会受此影响。
所以我们来到了中心问题 - 为什么初始 URLConnection InputStream(或 HttpClient InputStream)需要这么长时间来处理,而在本地创建的任何相同大小和内容的流都快几个数量级?我的意思是,初始响应已经在 RAM 中的某个地方,与刚从字节 [] 创建相同的流相比,我看不出为什么它的处理速度如此缓慢。
考虑到我必须解析数百万个条目和数千个这样的页面,几乎 1.5 秒/页的总处理时间似乎太长了。
有任何想法吗?
PS请询问是否需要更多代码-解析后我唯一要做的就是制作一个PreparedStatement并将条目以1000+包的形式放入JavaDB,性能还可以~200ms / 1000个条目,prb可以通过更多缓存进行优化但我没有仔细研究它。