Javascript RegExp:使用交替运算符组合模式或多次执行正则表达式

Javascript RegExp:使用交替运算符组合模式或多次执行正则表达式,javascript,regex,Javascript,Regex,我需要一个字符串来匹配几个模式中的一个。什么被认为是更好的做法?在交替运算符的帮助下组合图案|: const regexp = /(width)-(\d+)$|(height)-(\d+)$/ const matches = regexp.exec(string); 或者使用不同的模式多次执行正则表达式: const regexp = /(width)-(\d+)$/ const regexp2 = /(height)-(\d+)$/ let matches = regexp.exec(str

我需要一个字符串来匹配几个模式中的一个。什么被认为是更好的做法?在交替运算符的帮助下组合图案
|

const regexp = /(width)-(\d+)$|(height)-(\d+)$/
const matches = regexp.exec(string);
或者使用不同的模式多次执行正则表达式:

const regexp = /(width)-(\d+)$/
const regexp2 = /(height)-(\d+)$/
let matches = regexp.exec(string);
let matches2 = regexp.exec(string);
我喜欢的是,当多次执行正则表达式时,结果数组将始终具有相同的结构,而使用组合模式时,匹配高度宽度的结果将不同,因为宽度将匹配前两个捕获括号,但是高度最后两个

例如,如果字符串为
width-20
,则结果为:

[ 'width-20',
  'width',
  '20',
  undefined,
  undefined,
  index: 0,
  input: 'width-20' 
]
对于
高度-20

[ 'height-20',
  undefined,
  undefined,
  'height',
  '20',
  index: 0,
  input: 'height-20' 
]

但是从性能的角度来看,什么是更好的方法呢

首先,我认为第一个选项速度更快,但在
1E6
迭代中进行了一些测试后,我得出结论,使用或在RegExp中使用速度较慢~30-40%

能够在75-99毫秒内解决100万次迭代

const regexp = /(width)-(\d+)$/
const regexp2 = /(height)-(\d+)$/
let matches = regexp.exec(string);
let matches2 = regexp.exec(string);
const regexp = /(width)-(\d+)$|(height)-(\d+)$/
const matches = regexp.exec(string);
const regexp = /(width|height)-(\d+)$/
const matches = regexp.exec(string);
能够在120-140毫秒内解决100万次迭代

const regexp = /(width)-(\d+)$/
const regexp2 = /(height)-(\d+)$/
let matches = regexp.exec(string);
let matches2 = regexp.exec(string);
const regexp = /(width)-(\d+)$|(height)-(\d+)$/
const matches = regexp.exec(string);
const regexp = /(width|height)-(\d+)$/
const matches = regexp.exec(string);
编辑

使用@nnnnnn拥有的第三个选项:

能够在110-125毫秒内解决100万次迭代

const regexp = /(width)-(\d+)$/
const regexp2 = /(height)-(\d+)$/
let matches = regexp.exec(string);
let matches2 = regexp.exec(string);
const regexp = /(width)-(\d+)$|(height)-(\d+)$/
const matches = regexp.exec(string);
const regexp = /(width|height)-(\d+)$/
const matches = regexp.exec(string);

或者
/(宽度|高度)-(\d+)$/
@LazarevAlexandr是的,我已经测试过它比您的第二个选项慢,但比第一个选项快您需要担心性能的迭代次数有多少?答案是一百万次迭代,但是如果你只有一千次,或者一百次,那可能没关系。@nnnn谢谢,你的选择看起来更干净。当我意识到所涉及的迭代的实际数量时,我将根据您的考虑做出决定。没有规则或愚蠢的“最佳实践”,所有这些都取决于您的主题字符串以及最终代码的执行位置(浏览器X或Y、节点版本X、Y、z)。谢谢您的回答。我想知道测试结果是否相同,是否会有更多的模式。稍后我会尝试为自己做一些测试。很高兴它对您有所帮助),这也帮助我认识到|如果处理不当,可能会对性能产生影响)