-3

Let's say I have something like this in my code. I'm limited since I can't use anything that has been added to JavaScript after 2015. Still if you know something that is really good I would like to hear from you anyway.

const map = new HashMap(); 
map.putAll(someData);

// let in code
let keys = map.keySet();
for (let i = 0; i < keys.length; i++) {
  // Do something with each key e.g.
  something(keys[i];
}

What would be the best way to go through these keys because I try to avoid for whenever it is possible since there is usually something faster.

Antoni
  • 356
  • 5
  • 17
Stefan
  • 3
  • 3
  • you can use `while (i < keys.length)` – Antoni Jun 29 '20 at 12:54
  • 2
    I don't think a native for loop is slow. It may not be safe based on Indexing but speed is not usually an issue. Here is a jsbench sample for different types of iterations https://jsben.ch/giRjy. This being said, you should look into forEach, speed + safety – Rahul Kadukar Jun 29 '20 at 12:55
  • @RahulKadukar the `for` loop can be made *safe* (as you call it) by iterating backward. – Rafael Herscovici Jun 29 '20 at 12:57
  • for me `while` was faster than `for` with jsbench. Just use `while` – Antoni Jun 29 '20 at 12:59
  • @RahulKadukar Thanks I'll look into that. I did want to use `forEach` originally but it's not possible here with `keys`. – Stefan Jun 29 '20 at 13:00
  • https://jsben.ch/7GNqK I added `for of` to the benchmark – Antoni Jun 29 '20 at 13:07

1 Answers1

0

For loop isn't slow !, if you want to use an alternative way, you can use ForEach loop :

   var object = {
        1: "- something",
        2: "- something else",
    };
    
    Object.keys(object).forEach(function (key) {
        console.log(key, object[key]);
    });
mhannani
  • 492
  • 1
  • 5
  • 18
  • This is a comment not an answer – Antoni Jun 29 '20 at 13:08
  • Why it isn't ? i provide an alternative way to loop through keys . – mhannani Jun 29 '20 at 13:11
  • @HANNANI the question asks what the best way to go through keys is, you have provided "a way" of doing it, it may not be the best way of doing it. You have not provided any benchmarks or explained why your method is the quickest, hence this is not an answer. – Rahul Kadukar Jul 09 '20 at 12:54