views:

72

answers:

2

Hi,

My impl of fillRect much (> 3 times) slower than context2d.fillRect. How I can optimize my code or why builtin fillRect faster (some app acceleration?)?

My impl:

  __fillRect : function (data, x, y)//, r, g, b)
  {
    var w = this.__width * 4;
    var idx = x * 4+ y * w;
    var idx_1 = idx + 4;
    var idx_2 = idx + 8;
    var idx_3 = idx + w;
    var idx_4 = idx_3 + 4;
    var idx_5 = idx_3 + 8;
    var idx_6 = idx_3 + w;
    var idx_7 = idx_6 + 4;
    var idx_8 = idx_6 + 8;

    function __setPixelIdx (idx)
    {
      data[idx + 0] = 200;
      data[idx + 1] = 0;
      data[idx + 2] = 0;
      data[idx + 3] = 255;
    }

    __setPixelIdx (idx);
    __setPixelIdx (idx_1);
    __setPixelIdx (idx_2);
    __setPixelIdx (idx_3);
    __setPixelIdx (idx_4);
    __setPixelIdx (idx_5);
    __setPixelIdx (idx_6);
    __setPixelIdx (idx_7);
    __setPixelIdx (idx_8);

  },
+3  A: 

Your implementation is slower for a few reasons:

  • You are writing to an array and then copying and converting that into the canvas framebuffer.
  • context2d.fillRect is running native code, not interpreted or JIT compiled JavaScript.
  • context2d can potentially use graphics hardware to draw
  • You are writing single bytes at a time whereas even an unaccelerated native library could write whole int32 pixel values

My advice is use the native fillRect method unless you have a very good reason not too (e.g. doing your own shading or masking). You will not get anywhere near the speed of the library function.

Calling __setPixelIdx instead of doing the data accessing in the main __fillRect function probably isn't helping much.

andrewmu
Thanks a lot! It is just what I want to hear.
W55tKQbuRu28Q4xv
+1  A: 

Why you write a function that exists in native code? It is obvious that you can't compete with it in terms of speed.

galambalazs
My __setPixel 2 time faster than ctx.fillRect (x, y, 1, 1) and I try to impl fillRect by myself.
W55tKQbuRu28Q4xv