@SuppressLint("Range") public SendFrameTimeMtc selectFrameTime(long sceneStartTime) { SendFrameTimeMtc sendFrameTimeMtc = new SendFrameTimeMtc(); Cursor cursor = mRDB.query(TABLE_FRAMETIME, null, "scene_start_time=?", new String[]{String.valueOf(sceneStartTime)}, null, null, "_id", null); int batch = 0; long frameTime = 0; long curFrameTime = 0; if (cursor.getCount() > 0){ SendFrameTimeEntity sendFrameTimeEntity = new SendFrameTimeEntity(); while (cursor.moveToNext()) { if (sendFrameTimeEntity.getTs() == 0){ /** * 首次重置批次 */ frameTime = cursor.getLong(cursor.getColumnIndex("frame_time")); sendFrameTimeEntity.setTs(frameTime); batch = cursor.getInt(cursor.getColumnIndex("batch")); }else { if (batch == cursor.getInt(cursor.getColumnIndex("batch"))){ curFrameTime = cursor.getLong(cursor.getColumnIndex("frame_time")); sendFrameTimeEntity.getFtList().add(curFrameTime-frameTime); frameTime = curFrameTime; }else { // 批次不同,重置 sendFrameTimeMtc.getSendFrames().add(sendFrameTimeEntity); sendFrameTimeEntity = new SendFrameTimeEntity(); frameTime = cursor.getLong(cursor.getColumnIndex("frame_time")); sendFrameTimeEntity.setTs(frameTime); batch = cursor.getInt(cursor.getColumnIndex("batch")); } } } sendFrameTimeMtc.getSendFrames().add(sendFrameTimeEntity); } return sendFrameTimeMtc; }
时间: 2024-02-10 18:07:04 浏览: 59
这段代码看起来已经比较简洁,但是还是可以进行一些优化:
1. 可以使用 try-with-resources 语句来自动关闭 cursor,避免忘记关闭而导致的资源泄漏。
2. 可以将 cursor.getColumnIndex() 方法的调用移到循环外部,避免在循环中重复调用,提升效率。
3. 可以将重复的代码抽取成方法,提高代码的复用性和可读性。
下面是优化后的代码:
```
@SuppressLint("Range")
public SendFrameTimeMtc selectFrameTime(long sceneStartTime) {
SendFrameTimeMtc sendFrameTimeMtc = new SendFrameTimeMtc();
SendFrameTimeEntity sendFrameTimeEntity = new SendFrameTimeEntity();
try (Cursor cursor = mRDB.query(TABLE_FRAMETIME, null, "scene_start_time=?", new String[]{String.valueOf(sceneStartTime)}, null, null, "_id", null)) {
int batchIndex = cursor.getColumnIndex("batch");
int frameTimeIndex = cursor.getColumnIndex("frame_time");
while (cursor.moveToNext()) {
int batch = cursor.getInt(batchIndex);
long frameTime = cursor.getLong(frameTimeIndex);
if (sendFrameTimeEntity.getTs() == 0) {
/** 首次重置批次 */
sendFrameTimeEntity.setTs(frameTime);
sendFrameTimeEntity.setBatch(batch);
} else {
if (batch == sendFrameTimeEntity.getBatch()) {
long curFrameTime = frameTime;
sendFrameTimeEntity.getFtList().add(curFrameTime - sendFrameTimeEntity.getTs());
sendFrameTimeEntity.setTs(curFrameTime);
} else {
// 批次不同,重置
sendFrameTimeMtc.getSendFrames().add(sendFrameTimeEntity);
sendFrameTimeEntity = new SendFrameTimeEntity();
sendFrameTimeEntity.setTs(frameTime);
sendFrameTimeEntity.setBatch(batch);
}
}
}
sendFrameTimeMtc.getSendFrames().add(sendFrameTimeEntity);
}
return sendFrameTimeMtc;
}
```
注意:由于无法运行代码,以上修改可能存在错误,请仔细检查修改后的代码是否正确。
阅读全文