Is the poor performance of Excel VBA auto-instancing a myth?

前端 未结 1 1724
旧时难觅i
旧时难觅i 2021-02-13 19:52

The accepted wisdom is that using a construct like Dim dict As New Dictionary is poorer in performance than Dim dict As Dictionary / Set dict = New Dictionary

1条回答
  •  难免孤独
    2021-02-13 20:23

    I know there is the holy way over if it's okay or not to dim as new, but I've never heard of it being said to generate poor performance. The short answer is Not Really. Yes it does litter your code with unnessesary checks to see if it's not Nothing, but you wouldn't notice a speed difference thanks to today's machines. It's like saying "for looping over 10000 characters is faster than 10001. To start seeing any difference, you need to be looping your tests in higher terms, like millions and tens of millions.

    That being said Dim as New is frowned upon but not for performance reasons.

    • You lose the ability to control when it's initialized
    • You lose the ability to check if an object is Nothing
    • Speed difference or not, it does litter your code with unnessesary checking

    Granted if you are just using VBA to automate some worksheet stuff or manipulate data, you probably won't care about these, but the moment you look at more sophisticated code, losing the ability to test if an object is Nothing and not controlling when it's initialized is huge and can generate unexpected behavior, not to mention make testing a pain in the butt. All that for saving a few lines of code.

    Then there are the micro-optimizers who will argue that adding anything to your code that is not needed makes for poor performance. While they are right in some ways, you'll most likely saving 0.000000001 seconds in this case.

    0 讨论(0)
提交回复
热议问题