简体   繁体   English

一项功能与多项功能的性能

[英]Performance of one function vs. multiple

I have many drag and drop objects on the stage, and the default code snippet adds a new event listener and function to the stage for each object: 我在舞台上有很多拖放对象,默认代码段为舞台上的每个对象添加了一个新的事件侦听器和函数:

stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ReleaseToDrop(event:MouseEvent):void { instance_1.stopDrag(); }
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop_1);
function fl_ReleaseToDrop_1(event:MouseEvent):void { instance_2.stopDrag(); }
....

Would it be better or worse to put them all into one listener? 将它们全部放在一个听众中会更好还是更坏?

stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ReleaseToDrop(event:MouseEvent):void {
  instance_1.stopDrag();
  instance_2.stopDrag();
  ....
}

One function call is surely faster than multiple function calls. 一个函数调用肯定比多个函数调用快。 However, the difference here is going to be negligible. 但是,这里的差异可以忽略不计。

From a code readability stand-point, I would say the single function call you've shown is better. 从代码可读性的角度来看,我想说的是您展示的单个函数调用更好。


Generally, the way I like to do drag-and-drop is to add the mouseUp handler when I start the drag, and remove it immediately when dragging is completed. 通常,我喜欢拖放的方式是在开始拖动时添加mouseUp处理程序,并在完成拖动后立即将其删除。 For example: 例如:

instance1.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
instance2.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
instance3.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);

function mouseDown(e:MouseEvent):void {
    Sprite(e.currentTarget).startDrag();
    stage.addEventListener(MouseEvent.MOUSE_UP, mouseUp);
}

function mouseUp(e:MouseEvent):void {
    stopDrag();
    stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUp);
}

For a Flash timeline easy and efficient solution you simply keep reference to your object and that's about it: 对于Flash时间轴简单高效的解决方案,您只需保持引用对象即可,仅此而已:

stage.addEventListener(MouseEvent.MOUSE_UP, mouseUp);
instance1.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
instance2.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
instance3.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
var draggedObject:Sprite;

function mouseDown(e:MouseEvent):void 
{
    draggedObject = e.currentTarget as Sprite;
    if(draggedObject)
    {
        draggedObject.startDrag();
    }        
}

function mouseUp(e:MouseEvent):void 
{
    if(draggedObject)
    {
        draggedObject.stopDrag();
        draggedObject = null;
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM