构成长度为N的字符串的最有效方法是什么,其中从af,0-9中选择随机字符

gue*_*314 9 javascript performance performance-testing coding-efficiency

的要求是,以确定最有效的方法来呈现一个字符串,例如,"#1a2b3c",其中"1a2b3c"随机从该组中选择

"abcdef0123456789"

要么

["a", "b", "c", "d", "e", "f", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]


为了比较结果的一致性,弦.length应该是精确的7,如上面的例子所示.

确定过程时间的迭代次数应10000如下面的代码所示.


我们可以通过两个前瞻性的例子和基准来开始调查.这些方法的基准应包括在答案的文本中.请注意,如果可以使用更准确的基准测试,或者可以改进问题文本,请在评论时提出建议.相关:能够流利使用Javascript的人向我解释这里发生的事情简单.

function randColor() {
  return '#' + (function co(lor) {
    return (lor += [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'][Math.floor(Math.random() * 16)]) &&
      (lor.length == 6) ? lor : co(lor);
  })('');
}

console.time("random string recursion");

for (let i = 0; i < 10000; i++) {
  randColor()
}

console.timeEnd("random string recursion");

console.time("random string regexp");

for (let i = 0; i < 10000; i++) {
  "xxxxxx".replace(/x/g, function() {
    return "abcdef0123456789".charAt(Math.floor(Math.random() * 16))
  });
}

console.timeEnd("random string regexp");
Run Code Online (Sandbox Code Playgroud)

什么是最有效的,其中,效率被定义为必需的"速度"和"存储"资源的最小量,以实现具有返回的字符串.lengthN

速度和存储的效率是否随着N增加而降低?

nca*_*eli 6

另一种方法,假设字符介于两者之间[a-f0-9].它在速度和存储方面都很有效.

function randColor() {
  return '#' + (Math.floor(Math.random() * 16777216)).toString(16).padStart(6, '0');
}

console.time("random string hexa");

for (let i = 0; i < 10000; i++) {
  randColor()
}

console.timeEnd("random string hexa");
Run Code Online (Sandbox Code Playgroud)

我使用jsPerf将其速度与问题中描述的方法进行了比较.结果如下:https://jsperf.com/generating-hex-string-of-n-length

Chrome jsPerf Firefox jsPerf

  • 由于随机和地板的工作方式,它应该是16777216次.否则,#ftffff是不可能的. (2认同)