for-in vs Object.keys forEach without inherited properties

后端 未结 6 1940
萌比男神i
萌比男神i 2020-12-15 03:19

I was looking at a perf benchmark of Object.keys + forEach vs for-in with normal objects.

This benchmark shows that Obj

6条回答
  •  再見小時候
    2020-12-15 04:10

    I tested this today. For my purposes, getting the Object keys and then doing a plain old for loop was faster than doing a decrementing while or a for in loop. Feel free to change this template to test the different loops out for your individual case:

    //Helper functions
    function work(value) {
      //do some work on this value
    }
    
    function createTestObj(count) {
      var obj = {}
      while (count--) {
        obj["key" + count] = "test";
      }
      return obj;
    }
    
    //Tests
    function test_ObjKeyWhileDecrement(obj) {
      console.log("Time Started: ", new Date().getTime());
      var keys = Object.keys(obj),
        i = keys.length;
      while (i--) {
        work(obj[keys[i]]);
      }
      console.log("Time Finished: ", new Date().getTime());
    }
    
    function test_ObjKeyForLoop(obj) {
      console.log("Time Started: ", new Date().getTime());
      for (var i = 0, keys = Object.keys(obj); i < keys.length; i++) {
        work(obj[keys[i]]);
      }
      console.log("Time Finished: ", new Date().getTime());
    }
    
    function test_ForInLoop(obj) {
      console.log("Time Started: ", new Date().getTime());
      for (key in obj) {
        work(obj[key]);
      }
      console.log("Time Finished: ", new Date().getTime());
    }
    
    //Run the Tests
    var data = createTestObj(1000 * 100)
    console.log("Test Obj Key While Decrement Loop")
    test_ObjKeyWhileDecrement(data);
    console.log("Test Obj Key For Loop")
    test_ObjKeyForLoop(data);
    console.log("Test For In Loop")
    test_ForInLoop(data);

    You may want to run that in your actual environment to test instead of in a jsfiddle. Try multiple browsers also.

提交回复
热议问题