有人可以解释一下,为什么本机
JSON.parse()
或 Response: json()
方法的工作速度比 lossless-json
的解析方法慢?
我创建了示例进行比较。首先,您需要获取大 JSON。我使用了大约 100Mb 的文件。如果你愿意的话可以使用这个
https://fastupload.io/74707474ed41dc72
然后在这里玩
https://codepen.io/MaevskiyE/pen/vYwYPEq
并比较解析时间(在控制台中)
更新:经过进一步调查,我发现这不是lossless-json的优势,而是看起来像Chromium具体的JSON.parse方法实现。如果您在 Firefox 中打开相同的示例,本机 JSON.parse 将比无损 json 更快地完成工作。
当我将文件中的长和纬度从字符串更改为数字后,Chrome 也开始快速运行。 我的问题,也许有人知道浏览器之间的具体实现是什么?也许向 Chromium 团队报告问题是有意义的
new Vue({
el: "#app",
data() {
return {};
},
methods: {
handleFile() {
console.log("STARTED JSON.parse", luxon.DateTime.utc().toISO());
const input = document.getElementById("fileInput");
const reader = new FileReader();
reader.onload = (event) => {
const csvText = event.target.result;
this.processCSV(csvText);
};
reader.readAsText(input.files[0]);
},
processCSV(csvText) {
const nativeParse = JSON.parse(csvText);
console.log("PARSED JSON.parse", luxon.DateTime.utc().toISO());
},
handleFile2() {
console.log("STARTED lossless-json", luxon.DateTime.utc().toISO());
const input = document.getElementById("fileInput");
const reader = new FileReader();
reader.onload = (event) => {
const csvText = event.target.result;
this.processCSV2(csvText);
};
reader.readAsText(input.files[0]);
},
processCSV2(csvText) {
const nativeParse = LosslessJSON.parse(csvText);
console.log("PARSED lossless-json", luxon.DateTime.utc().toISO());
}
}
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/umd/lossless-json.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.9/vue.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="app">
<div>
<input type="file" id="fileInput" />
</div>
<br />
<div>
<button @click="handleFile()">Parse with native JSON.parse</button>
<button @click="handleFile2()">Parse with lossless-json</button>
</div>
</div>
</body>
</html>
我想我找到了答案。 Lossless-json 使用名为 LosslessNumber 的类,将数值存储为字符串。因为我的 JSON 中有很多数字,lossless-json 甚至不尝试对其进行任何数学运算。我猜..