- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
来自 flutter doc :
class CounterStorage {
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/counter.txt');
}
Future<int> readCounter() async {
try {
final file = await _localFile;
// Read the file
String contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If we encounter an error, return 0
return 0;
}
}
Future<File> writeCounter(int counter) async {
final file = await _localFile;
// Write the file
return file.writeAsString('$counter');
}
}
两者都是 readCounter()
和 writeCounter()
调用_localPath
每次他们被调用时都会吸气。
我的问题是:
这不是有点浪费吗?等待_localFile
不是更好吗?在 CounterStorage
的构造函数中,并将其存储在类成员中,而不是获取 _localPath
和 _localPath
每一次?
有人可以建议这样的实现吗?
最佳答案
这取决于你所说的浪费,以及getApplicationDocumentsDirectory
的契约。
例如,如果 getApplicationDocumentsDirectory()
有可能在下次调用时返回一个不同的路径(例如,如果一个新用户登录,可能 - 我不确定细节)那么这是完全正确的。
如果保证这个值永远不会改变,可能进一步优化,但显示优化可能不是示例文档的目标。如果您有兴趣,我能想到的两个想法是:
static final
字段:class CounterStorage {
// Static fields in Dart are lazy; this won't get sent until used.
static final _localPath = getApplicationDocumentsDirectory().then((p) => p.path);
// ...
}
如果 CounterStorage
有其他方法或字段有用而不等待 _localPath
被解析,这是我的偏好。在上面的例子中,没有,所以我更喜欢:
static
async
方法来创建CounterStorage
import 'package:meta/meta.dart';
class CounterStorage {
// You could even combine this with the above example, and make this a
// static final field.
static Future<CounterStorage> resolve() async {
final localPath = await getApplicationDocumentsDirectory();
return new CounterStorage(new File(this.localPath));
}
final File _file;
// In a test you might want to use a temporary directory instead.
@visibleForTesting
CounterStorage(this._file);
Future<int> readCount() async {
try {
final contents = await _file.readAsString();
return int.parse(contents);
} catch (_) {
return 0;
}
}
}
这使得检索 File
的过程可能在每个应用程序中发生一次。
关于dart - 下面的Flutter读写文件文档有没有浪费实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51254753/
Webassembly:我找不到此语法的引用 (f32.const -0x0p+0) .它代表什么数字/位模式?它来自引用解释器的测试文件: https://github.com/WebAssembl
分析后,我发现我的程序有很大一部分内存被多重虚拟继承所浪费。 这是 MCVE 来演示问题 ( http://coliru.stacked-crooked.com/a/0509965bea19f8d9
如何在通过多个加载语句插入记录时避免跳过主 ID? 我通过 LOAD 语句将包含 150 条记录的文件插入到表中。 插入后表中最后一个primary id为150。 现在,当我通过加载语句插入另一个包
我开始了一份新工作,我正在工作的项目部分的结构非常奇怪。每个页面都是一个 .Net aspx 页面,并且加载得很好,但在加载时并没有真正执行任何操作。一切实际上都是从 jquery document.
我是一名优秀的程序员,十分优秀!