通过 2 组或更多组数据有效地优化代码 运行

Optimizing code to run through 2 or more sets of data efficiently

你好,我遇到了这个问题,这个程序需要很长时间才能运行 运行,我的任务是让它运行得更快

interface Payroll {
  empNo: string;
  vacationDays: number;
}

interface AddressBook {
  empNo: string;
  email: string;
}

interface WorkHistory {
  empNo: string;
  name: string;
  yearsEmployed: number;
}

interface EmailApi {
  sendEmail(email: string, body: string);
}

// We haved decided to grant bonus vacation to every employee, 1 day per year of experience
// we need to email them a notice
EmailVacationGrant(
  emailApi: EmailApi,
  workHistory: WorkHistory[],
  addressBook: AddressBook[],
  payroll: Payroll[],
) {
  for(int i=0; i<workHistory.length; ++i) {
    let employee = wh[i];
    let address = addressBook.find(x => x.empNo==employee.empNo);
    let payroll = payroll.find(x => x.empNo==employee.empNo);

    let newVacationBalance = employee.yearsEmployed + payroll.vacationDays;
    emailApi.sendEmail(
      address.email,
      `Dear ${employee.name}\n` +
      `based on your ${employee.yearsEmployed} years of employment, you have been granted ${employee.yearsEmployed} days of vacation, bringing your total to ${newVacationBalance}`);
  }
}

经过一些研究后,我了解到即使不是所有浏览器,大多数浏览器也不喜欢 .find 方法,而更喜欢通用的 for 循环。知道这一点后,我认为将所有内容都放在一个界面中是合适的。我的解决方法如下

interface WorkHistory {
  empNo: string;
  vacationDays: number;
  email: string;
  name: string;
  yearsEmployed: number;
}

interface EmailApi {
  sendEmail(email: string, body: string);
}

// We haved decided to grant bonus vacation to every employee, 1 day per year of experience
// we need to email them a notice
EmailVacationGrant(
  emailApi: EmailApi,
  workHistory: WorkHistory[],
) {
  for(int i=0; i<workHistory.length; ++i) { // in js a for loop is much faster the .find however I wanted to stick with to make sure the time complexity wasnt too huge
    let employee = wh[i];
    let address = employee.email;
    let payroll = employee.payroll;

    let newVacationBalance = employee.yearsEmployed + employee.vacationDays;
    emailApi.sendEmail(
      employee.email,
      `Dear ${employee.name}\n` +
      `based on your ${employee.yearsEmployed} years of employment, you have been granted ${employee.yearsEmployed} days of vacation, bringing your total to ${newVacationBalance}`);
  }
}

有没有其他更快的方法,尤其是不需要我弄乱接口的方法

Array.find 的时间复杂度应该是 O(n),这在您的情况下已经相当不错了,而且不会变得更好。正如您已经尝试过的那样,在您的情况下,最好的解决方案是扩展接口。如果您无法更改它们,则可以扩展它们。 我们不太了解您的数据模型以及您如何获取员工的这些详细信息,但在用户体验方面,最好的解决方案始终是您通过单个请求获得所需的数据。如果这是不可能的,可以在 运行 进入您的方法之前提前加载和映射此数据。

您提供的代码很好,您可能希望将所有出现的 let 更改为 const