代码之家  ›  专栏  ›  技术社区  ›  Adriana

在函数中循环或多次调用函数,什么更快?

  •  3
  • Adriana  · 技术社区  · 15 年前

    basicly I've got an array and want to call the same function for each element. Which way is it faster?

    foreach($elemeents as $element){
        callFunction($element);
    }
    

    function callFunction($leements){
        foreach($elements as $element){
            //do something
        }
    }
    

    我只是个初学者

    6 回复  |  直到 15 年前
        1
  •  3
  •   Blorgbeard    15 年前

    Probably slightly faster with the loop inside the function, as there is a (slight) cost to each function call. However, it won't make much difference.

    这真的是过早的优化,而且 the root of all evil .

    You should write it so it is clear, then if it's too slow, figure out where it's slow and optimize that.

        2
  •  0
  •   Michael Borgwardt    15 年前

    This is the kind of micro-optimization that most likely does not matter. Do whatever leads to cleaner code.

        3
  •  0
  •   Tom Gullen    15 年前

    They are essentially the same, and any time execution difference will be negliable. It comes down to preference.

        4
  •  0
  •   pinaki    15 年前

    I dont think there would be much of a difference between the two anyway, but from what I recollect of function stack calling, the first method should take longer.

        5
  •  0
  •   Pierre Gardin    15 年前

    In every language I know, using loops is faster, because of the operations involved when calling a function (like adding it to the stack).

    However, you should not think about the performance before the actual performance issues arise. Think in terms of design, code clarity, and low maintenance efforts.

        6
  •  0
  •   Gumbo    15 年前

    简而言之:第二个应该更快。