最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I efficiently copy the entries from one Map to another Map where the target Map has multiple reference vari

programmeradmin1浏览0评论

I have found a way to copy the entries from one Map to another Map where the target Map has multiple reference variables but I suspect it is not optimal. Is there a shorter/more efficient way?

const mapFrom = new Map([[1, 'from']]);
const mapTo = new Map([[1, 'to']]);
const refMapTo = mapTo;
mapTo.clear();
for (const [key, value] of mapFrom) mapTo.set(key, value);
if (mapTo.get(1) === mapFrom.get(1) && mapTo === refMapTo) {
  console.log('this code works but can I avoid the `for...of` iteration?');
}

I have found a way to copy the entries from one Map to another Map where the target Map has multiple reference variables but I suspect it is not optimal. Is there a shorter/more efficient way?

const mapFrom = new Map([[1, 'from']]);
const mapTo = new Map([[1, 'to']]);
const refMapTo = mapTo;
mapTo.clear();
for (const [key, value] of mapFrom) mapTo.set(key, value);
if (mapTo.get(1) === mapFrom.get(1) && mapTo === refMapTo) {
  console.log('this code works but can I avoid the `for...of` iteration?');
}
Share Improve this question asked Feb 1 at 9:03 user2309803user2309803 6556 silver badges18 bronze badges 3
  • 1 Why you want to avoid for-of? – Ivan Yonkov Commented Feb 1 at 9:15
  • @IvanYonkov because I suspect mapFrom will grow very large and browser performance could be degraded – user2309803 Commented Feb 1 at 9:18
  • 3 There's no way to copy (at later stage) without looping through the values. Either mapTo must be a reference to mapFrom from the beginning or you need to have this loop one way or another – Ivan Yonkov Commented Feb 1 at 9:31
Add a comment  | 

1 Answer 1

Reset to default 1

I don't think there's anything particularly wrong with using for...of. If you really want to avoid it, you could try using forEach, but opinions on this are divided.

Here are a few related topics from earlier.

  • Loop (for each) over an array in JavaScript - StackOverflow
  • Loops- forEach, for, for....of, for...in - StackOverflow
  • Why should forEach be preferred over regular iterators? - StackOverflow
  • Should one use for-of or forEach when iterating through an array? - StackOverflow
  • What is the most efficient way to deep clone an object in JavaScript? - StackOverflow

I don't know the goal of the task. If the goal is simply copying, using the constructor or forEach seems like a good solution. Among the mentioned posts, there are a few that go quite deep into the topic, and I can only recommend reading all of them.

// Constants for map size and test iterations
const MAP_SIZE = 100000;
const TEST_RUNS = 100;

// Create a map with MAP_SIZE entries
const mapFrom = new Map();
for (let i = 0; i < MAP_SIZE; i++) {
  mapFrom.set(i, `value_${i}`);
}

// Function to run tests TEST_RUNS times and calculate average, min, and max
function test(testName, testFunction) {
  const times = [];

  // Run the test TEST_RUNS times
  for (let i = 0; i < TEST_RUNS; i++) {
    const start = performance.now();
    testFunction();
    const end = performance.now();
    times.push(end - start);
  }

  // Calculate average, min, and max
  const avg = times.reduce((a, b) => a + b, 0) / times.length;
  const min = Math.min(...times);
  const max = Math.max(...times);

  // Log the results
  console.log(`${testName}:`);
  console.log(`  Average Time: ${avg.toFixed(2)} ms`);
  console.log(`  Min Time: ${min.toFixed(2)} ms`);
  console.log(`  Max Time: ${max.toFixed(2)} ms`);
}

// 1. Using Map constructor to copy
test('Map Constructor', () => {
  const mapToConstructor = new Map(mapFrom);
});

// 2. Using for...of loop to copy
test('for...of loop', () => {
  const mapToForOf = new Map();
  for (const [key, value] of mapFrom) {
    mapToForOf.set(key, value);
  }
});

// 3. Using forEach to copy
test('forEach', () => {
  const mapToForEach = new Map();
  mapFrom.forEach((value, key) => {
    mapToForEach.set(key, value);
  });
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论