Is it better coding practice to define variables outside a foreach even though more verbose?

前端 未结 12 2250
栀梦
栀梦 2020-12-10 10:39

In the following examples:

  • the first seems more verbose but less wasteful of resources
  • the second is less verbose bu
12条回答
  •  醉话见心
    2020-12-10 11:22

    Depending on language and compiler it may or may not be the same. For C# I expect the resulting code to be very similar.

    My own philosophy on this is simple:

    Optimize for ease of understanding.

    Anything else is premature optimization! The biggest bottleneck in most development is time and attention of the developer. If you absolutely must squeeze out every last CPU cycle then by all means do so, but unless you have a compelling business need to do or are writing a critical component (common library, operating system kernel, etc) you are better off waiting until you can benchmark the finished program. At that time optimizing a few of the most costly routines is justified, before then it's almost certainly a waste of time.

提交回复
热议问题