【问题标题】:Iteration as array but still accessible by a key迭代为数组,但仍可通过键访问
【发布时间】:2018-11-01 09:58:03
【问题描述】:

我正在为简单的 2D 游戏编写自己的游戏引擎,并希望迭代子项,但出于某种原因,我想通过键访问每个项目。

也许有人知道以下我的问题的任何好的解决方案?

问题 #1

我不能使用Object.keys and for-in,因为简单的数组迭代具有 5 倍的性能提升。性能至关重要。

问题 #2

我想通过将子对象传递给函数来轻松添加/删除子对象: scene.add(child); scene.remove(child);

解决方案 #1?

我可以创建包含子 arrayobject 的数据结构。使用 add/remove 方法同时填充数组和对象。当然,在更改children 属性的情况下,你会破坏这些东西,但不是我的情况,你必须使用添加/删除。

实例

渲染。每个着色器程序都有子数组。

_render(...args) {
    const [gl, scene, camera] = args;
    const { childrenByShaderProgram } = scene;
    const dt = 0;

    gl.clearColor(0, 0, 0, 1);
    gl.clear(gl.COLOR_BUFFER_BIT);

    camera.updateViewMatrix();

    scene.beforeUpdate(dt);

    Object.keys(childrenByShaderProgram).forEach(uuid => {
      const children = childrenByShaderProgram[uuid];
      const sp = children[0].shaderProgram;

      // Per shader program rendering.
      this._useShaderProgram(gl, sp);

      // Update view matrix uniform value.
      sp.updateUniform('u_v', camera.viewMatrix);

      for (let j = 0, len = children.length; j < len; j += 1) {
        const child = children[j];

        // Update attributes and uniforms values.
        scene.updateEachChild(child, dt);

        // Apply changes by binding uniforms and attributes.
        sp.bindUniforms(gl);
        sp.bindAttributes(gl);

        // tbd @andytyurin texture implementation should be here.
        gl.drawArrays(gl.TRIANGLE_STRIP, 0, Math.floor(child.vertices.length / 2));
      }
    });

    scene.afterUpdate(dt);

    window.requestAnimationFrame(() => this._render(...args));
  }

接下来会更难...scene.js

export class Scene {
  constructor() {
    this.childrenByShaderProgram = {};
  }

  add(child) {
    const { children } = child;

    if (children && children.legnth) {
      // Container object.
      for (let i = 0, l = children.length; i < l; i += 1) {
        const nestedChild = children[0];
        const nestedChildren = nestedChild.children;

        // Children recursion.
        if (nestedChildren && nestedChildren.length) {
          this.add(nestedChild);
        } else {
          this._addChild(nestedChild);
        }
      }
    } else {
      this._addChild(child);
    }
  }

  remove(child) {
    const { children } = child;

    if (children && children.legnth) {
      // Container object.
      for (let i = 0, l = children.length; i < l; i += 1) {
        const nestedChild = children[0];
        const nestedChildren = nestedChild.children;

        // Children recursion.
        if (nestedChildren && nestedChildren.length) {
          this.remove(nestedChild);
        } else {
          this._removeChild(nestedChild);
        }
      }
    } else {
      this._removeChild(child);
    }
  }

  _addChild(child) {
    const spUuid = child.shaderProgram.uuid;

    if (child.renderingIdx) {
      throw new Error(
        'Could not add child as it is already added to the scene'
      );
    }

    this.childrenByShaderProgram[spUuid] =
      this.childrenByShaderProgram[spUuid] || [];

    child.renderingIdx = this.childrenByShaderProgram[spUuid].length;
    this.childrenByShaderProgram[spUuid].push(child);
  }

  _removeChild(child) {
    const spUuid = child.shaderProgram.uuid;
    const { renderingIdx } = child;

    if (!renderingIdx) {
      throw new Error(
        'Could not remove child which has not been added to the scene'
      );
    }

    const shaderProgramChildren = this.childrenByShaderProgram[spUuid];
    const lenMinusOne = shaderProgramChildren.length - 1;

    if (renderingIdx === 0) {
      this.childrenByShaderProgram[spUuid] = shaderProgramChildren.slice(1);
    } else if (renderingIdx === lenMinusOne) {
      this.childrenByShaderProgram[spUuid] = shaderProgramChildren.slice(
        0,
        lenMinusOne
      );
    } else {
      this.childrenByShaderProgram[spUuid] = [
        ...shaderProgramChildren.slice(0, renderingIdx),
        ...shaderProgramChildren.slice(renderingIdx + 1)
      ];
    }
  }

  beforeUpdate(children, dt) {}

  updateEachChild(child, dt) {
    // Make appropriate calculations of matrices.
    child.update();
  }

  afterUpdate(children, dt) {}
}

export default Scene;

在示例中,我使用renderingIdx 更快地从数组中删除子元素,但我不想在每个子元素中保留任何属性。因此,作为替代方案,我可以将子项保留在 key-valueArray 两种变体中。它将在渲染时提供相同的性能,以及在场景中添加和删除子项的相同性能。

谢谢!

【问题讨论】:

  • 我只是建议维护一个单独的对象键数组,但看起来这是您的第一个计划,我会尝试一下,看看它与 for..in 的性能相比如何。跨度>
  • @PatrickRoberts forEach 与简单的for 相比速度较慢。我不能使用array.entries(),我需要使用键,而不是索引。但是使用object.entries() 的想法看起来很有趣,但仍然需要比较性能。
  • @AndyTyurin Object.prototype.entries() 实际上已从规范中删除,不幸的是。您可以实现一个 polyfill,但它不会像您预期的那样高效。可用的只是静态的Object.entries(),它创建了一个键/值对数组并且不是惰性的。
  • @PatrickRoberts 好吧,使用Object.keys 看起来离迭代不远了。顺便说一句,我会尝试在主题中放置一些代码。
  • @Ninjaneer 对不起,我错过了为什么我们需要将数组转换为对象?

标签: javascript arrays object key-value for-in-loop


【解决方案1】:

您想出的解决方案就是要走的路。要跟踪密钥,最好编写一个包装类:

class LookupArray {
 constructor(key, ...entries) {
  this.key = key;
  this.array = [];
  this.hash = {};
  this.push(...entries);
  }
  push(...entries) {
   for(const entry of entries) {
     this.hash[entry[this.key]] = entry;
     this.array.push(entry);
    }
   return entry.length;
  }
  get(id) {
  return this.hash[id] || this.array[id];
  }
}

这样就可以了:

const lookup = new LookupArray("length", "abcd", "defghi");
console.log(
  lookup.get(0), // "abcd"
  lookup.get(4), // "abcd"
);

for(const entry of lookup.array)
  console.log(entry);

但我想您可以通过 cmets 中所述的Object.entries 以更少的内存实现类似的性能。

【讨论】:

  • 顺便说一句,使用非严格类型的后备(hash[id],其中id 应为字符串,array[id],其中id 应为索引) , 可能会阻止函数的可能优化。也许应该将其拆分为两个函数getKey()getIndex(),因为无论如何调用代码都不应该混合这两种情况。
  • 好主意,但它是如何工作的? this.hash[entry[this.key]] = entry; 条目应该是 String,因为我们使用的是 for-of 和字符串数组。
  • 看起来和解决方案#1很相似
  • @PatrickRoberts 这更像是概念验证而不是最终版本,是的,我收到了通知...谢谢
  • @AndyTyurin 可能这对对象最有意义,但对于字符串,它的输入更少:)
猜你喜欢
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
  • 2018-09-02
  • 1970-01-01
  • 2021-07-18
相关资源
最近更新 更多