Skip to content

Instantly share code, notes, and snippets.

@milahu
Last active Jun 2, 2021
Embed
What would you like to do?
get last item / key / value in map #jsbench #jsperf (https://jsbench.github.io/#7992a793df12b1ee16beaef7a9863c68) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>get last item / key / value in map #jsbench #jsperf</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/1.0.0/benchmark.min.js"></script>
<script src="./suite.js"></script>
</head>
<body>
<h1>Open the console to view the results</h1>
<h2><code>cmd + alt + j</code> or <code>ctrl + alt + j</code></h2>
</body>
</html>
"use strict";
(function (factory) {
if (typeof Benchmark !== "undefined") {
factory(Benchmark);
} else {
factory(require("benchmark"));
}
})(function (Benchmark) {
var suite = new Benchmark.Suite;
Benchmark.prototype.setup = function () {
const map = new Map();
for (let i = 0; i < 100; i++) {
map.set(
"key_"+Math.random(),
"value_"+Math.random()
);
}
const F1 = {};
F1.getLastItemInMap = map => Array.from(map)[map.size-1];
F1.getLastKeyInMap = map => Array.from(map)[map.size-1][0];
F1.getLastValueInMap = map => Array.from(map)[map.size-1][1];
const F2 = {};
F2.lastItemInMap = map => Array.from(map).pop();
F2.lastKeyInMap = map => Array.from(map.keys()).pop();
F2.lastValueInMap = map => Array.from(map.values()).pop();
const F3 = {};
F3.lastItemInMap = map => [...map].pop();
F3.lastKeyInMap = map => [...map.keys()].pop();
F3.lastValueInMap = map => [...map.values()].pop();
};
suite.add("F1.getLastItemInMap(map);", function () {
F1.getLastItemInMap(map);
});
suite.add("F1.getLastKeyInMap(map);", function () {
F1.getLastKeyInMap(map);
});
suite.add("F1.getLastValueInMap(map);", function () {
F1.getLastValueInMap(map);
});
suite.add("F2.lastItemInMap(map);", function () {
F2.lastItemInMap(map);
});
suite.add("F2.lastKeyInMap(map);", function () {
F2.lastKeyInMap(map);
});
suite.add("F2.lastValueInMap(map);", function () {
F2.lastValueInMap(map);
});
suite.add("F3.lastItemInMap(map);", function () {
F3.lastItemInMap(map);
});
suite.add("F3.lastKeyInMap(map);", function () {
F3.lastKeyInMap(map);
});
suite.add("F3.lastValueInMap(map);", function () {
F3.lastValueInMap(map);
});
suite.on("cycle", function (evt) {
console.log(" - " + evt.target);
});
suite.on("complete", function (evt) {
console.log(new Array(30).join("-"));
var results = evt.currentTarget.sort(function (a, b) {
return b.hz - a.hz;
});
results.forEach(function (item) {
console.log((idx + 1) + ". " + item);
});
});
console.log("get last item / key / value in map #jsbench #jsperf");
console.log(new Array(30).join("-"));
suite.run();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment