有条件的初始化是如何处理的,是它一个很好的做法? [英] How is conditional initialization handled and is it a good practice?

查看:146
本文介绍了有条件的初始化是如何处理的,是它一个很好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试几种可能的做法之间作出选择。比方说,我的功能的数,如果()块,对数据的工作,这是唯一的它们。


  • 我应该声明和初始化本地(为块)的块中的数据?这是否有运行时性能成本(由于在堆栈中分配运行时)?


  • 或者我应该声明和/或初始化在函数入口的所有变量,所以这是在一个做的,可能是速度更快,操作块?


  • 或者我应该单独在不同的功能,如果()块,即使他们是一对夫妇只排长队的,只有在程序中使用吗?


还是我ovelooking另外,清洁,选择吗?是个问题,即使在它的电流,一般形式回答的?


解决方案

  

我应该声明和初始化本地(该块)的数据块中?


绝对:这往往使程序的可读性。


  

这是否有运行时性能成本(由于在堆栈中分配运行时)?


没有:所有分配完成前期 - 堆栈中的空间保留给在输入函数的所有分支的变量,而不是输入分支时。此外,这甚至可以为您节省一些空间,因为在非重叠枝分配给变量的空间可被编译器重复使用。


  

或者我应该声明和/或初始化在函数入口的所有变量,所以这是在一个做的,可能是速度更快,操作块?


没有,这不是更快,并且可以稍微浪费。


  

或者我应该单独在不同的功能,如果()块,即使他们是一对夫妇只排长队的,只有在程序中使用呢?


这很可能会对你的程序可读性产生负面影响。

I am trying to decide between several possible practices. Say, my function has a number of if() blocks, that work on data, that is unique to them.

  • Should I declare and initialize the local (for the block) data inside the block? Does this have runtime performance cost (due to runtime allocation in the stack)?

  • Or should I declare and/or initialize all variables at function entry, so that is is done in one, possibly faster, operation block?

  • Or should I seperate the if() blocks in different functions, even though they are only a couple of lines long and used only one in the program?

Or am I ovelooking another, cleaner, option? Is the question even answerable in it's current, general form?

解决方案

Should I declare and initialize the local (for the block) data inside the block?

Absolutely: this tends to make programs more readable.

Does this have runtime performance cost (due to runtime allocation in the stack)?

No: all allocations are done upfront - the space on the stack is reserved for variables in all branches upon entering a function, not when the branch is entered. Moreover, this could even save you some space, because the space allocated for variables in non-overlapping branches can be reused by the compiler.

Or should I declare and/or initialize all variables at function entry, so that is is done in one, possibly faster, operation block?

No, this is not faster, and could be slightly more wasteful.

Or should I seperate the if() blocks in different functions, even though they are only a couple of lines long and used only one in the program?

That would probably have a negative impact on readability of your program.

这篇关于有条件的初始化是如何处理的,是它一个很好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆