经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
JavaScript代码优化技巧示例详解
来源:jb51  时间:2022/8/15 16:59:15  对本文有异议

引言

我们先引入一句话:

代码主要是为了写给人看的,而不是写给机器看的,只是顺便也能用机器执行而已。

代码和语言文字一样是为了表达思想、记载信息,所以写得清楚能更有效地表达。本文多数总结自《重构:改善既有代码的设计(第2版)》我们直接进入正题,上代码!

提炼函数

what

将一段代码提炼到一个独立的函数中,并以这段代码的作用命名。

where

如果需要花时间浏览一段代码才能弄清楚它到底要干什么,那么这时候就应该将其提炼到一个函数中,并根据它所做的事命名。以后再读这段代码时,一眼就能知道这个函数的用途。

how

  1. // ==================重构前==================
  2. function printOwing(invoice) {
  3. let outstanding = 0;
  4. console.log("***********************");
  5. console.log("**** Customer Owes ****");
  6. console.log("***********************");
  7. }
  8. // ==================重构后==================
  9. function printOwing(invoice) {
  10. let outstanding = 0;
  11. printBanner()
  12. }
  13. function printBanner() {
  14. console.log("***********************");
  15. console.log("**** Customer Owes ****");
  16. console.log("***********************");
  17. }

函数参数化

what

以参数的形式传入不同的值,消除重复函数

where

如果发现两个函数逻辑非常相似, 只有一些字面量值不同, 可以将其合并成一个函数, 以参数的形式传入不同的值, 从而消除重复。

how

  1. // ==================重构前==================
  2. // 点击异常项
  3. clickFaultsItem(item){
  4. this.$u.route({
  5. url:'xxx',
  6. params:{
  7. id: item.id,
  8. type: '异常'
  9. }
  10. })
  11. }
  12. // 点击正常项
  13. clickNormalItem(item){
  14. this.$u.route({
  15. url:'xxx',
  16. params:{
  17. id: item.id,
  18. type: '正常'
  19. }
  20. })
  21. }
  22. // ==================重构后==================
  23. clickItem(id, type){
  24. this.$u.route({
  25. url:'xxx',
  26. params:{id, type}
  27. })
  28. }

使用策略模式替换“胖”分支

what

使用策略模式替换“胖胖”的if-else或者switch-case

where

当if-else或者switch-case分支过多时可以使用策略模式将各个分支独立出来

how

  1. // ==================重构前==================
  2. function getPrice(tag, originPrice) {
  3. // 新人价格
  4. if(tag === 'newUser') {
  5. return originPrice > 50.1 ? originPrice - 50 : originPrice
  6. }
  7. // 返场价格
  8. if(tag === 'back') {
  9. return originPrice > 200 ? originPrice - 50 : originPrice
  10. }
  11. // 活动价格
  12. if(tag === 'activity') {
  13. return originPrice > 300 ? originPrice - 100 : originPrice
  14. }
  15. }
  16. // ==================重构后==================
  17. const priceHandler = {
  18. newUser(originPrice){
  19. return originPrice > 50.1 ? originPrice - 50 : originPrice
  20. },
  21. back(originPrice){
  22. return originPrice > 200 ? originPrice - 50 : originPrice
  23. },
  24. activity(originPrice){
  25. return originPrice > 300 ? originPrice - 100 : originPrice
  26. }
  27. }
  28. function getPrice(tag, originPrice){
  29. return priceHandler[tag](originPrice)
  30. }

提炼变量

what

提炼局部变量替换表达式

where

一个表达式有可能非常复杂且难以阅读。 这种情况下, 可以提炼出一个局部变量帮助我们将表达式分解为比较容易管理的形式 ,这样的变量在调试时也很方便。

how

  1. // ==================重构前==================
  2. function price(order) {
  3. //价格 = 商品原价 - 数量满减价 + 运费
  4. return order.quantity * order.price -
  5. Math.max(0, order.quantity - 500) * order.price * 0.05 +
  6. Math.min(order.quantity * order.price * 0.1, 100);
  7. }
  8. // ==================重构后==================
  9. function price(order) {
  10. const basePrice = order.quantity * order.price;
  11. const quantityDiscount = Math.max(0, order.quantity - 500) * order.price * 0.05;
  12. const shipping = Math.min(basePrice * 0.1, 100);
  13. return basePrice - quantityDiscount + shipping;
  14. }

内联变量

what

用变量右侧表达式消除变量,这是提炼变量的逆操作

where

当变量名字并不比表达式本身更具表现力时可以采取该方法

how

  1. // ==================重构前==================
  2. let basePrice = anOrder.basePrice;
  3. return (basePrice > 1000);
  4. // ==================重构后==================
  5. return anOrder.basePrice > 1000

封装变量

what

将变量封装起来,只允许通过函数访问

where

对于所有可变的数据, 只要它的作用域超出单个函数,就可以采用封装变量的方法。数据被使用得越广, 就越是值得花精力给它一个体面的封装。

how

  1. // ==================重构前==================
  2. let defaultOwner = {firstName: "Martin", lastName: "Fowler"};
  3. // 访问
  4. spaceship.owner = defaultOwner;
  5. // 赋值
  6. defaultOwner = {firstName: "Rebecca", lastName: "Parsons"};
  7. // ==================重构后==================
  8. function getDefaultOwner() {return defaultOwner;}
  9. function setDefaultOwner(arg) {defaultOwner = arg;}
  10. // 访问
  11. spaceship.owner = getDefaultOwner();
  12. // 赋值
  13. setDefaultOwner({firstName: "Rebecca", lastName: "Parsons"});

拆分阶段

what

把一大段行为拆分成多个顺序执行的阶段

where

当看见一段代码在同时处理两件不同的事, 可以把它拆分成各自独立的模块, 因为这样到了需要修改的时候, 就可以单独处理每个模块。

how

  1. // ==================重构前==================
  2. function priceOrder(product, quantity, shippingMethod) {
  3. const basePrice = product.basePrice * quantity;
  4. const discount = Math.max(quantity - product.discountThreshold, 0)
  5. * product.basePrice * product.discountRate;
  6. const shippingPerCase = (basePrice > shippingMethod.discountThreshold)
  7. ? shippingMethod.discountedFee : shippingMethod.feePerCase;
  8. const shippingCost = quantity * shippingPerCase;
  9. const price = basePrice - discount + shippingCost;
  10. return price;
  11. }
  12. /*
  13. 该例中前两行代码根据商品信息计算订单中与商品相关的价格, 随后的两行则根据配送信息计算配送成本。
  14. 将这两块逻辑相对独立后,后续如果修改价格和配送的计算逻辑则只需修改对应模块即可。
  15. */
  16. // ==================重构后==================
  17. function priceOrder(product, quantity, shippingMethod) {
  18. const priceData = calculatePricingData(product, quantity);
  19. return applyShipping(priceData, shippingMethod);
  20. }
  21. // 计算商品价格
  22. function calculatePricingData(product, quantity) {
  23. const basePrice = product.basePrice * quantity;
  24. const discount = Math.max(quantity - product.discountThreshold, 0)
  25. * product.basePrice * product.discountRate;
  26. return {basePrice, quantity, discount};
  27. }
  28. // 计算配送价格
  29. function applyShipping(priceData, shippingMethod) {
  30. const shippingPerCase = (priceData.basePrice > shippingMethod.discountThreshold)
  31. ? shippingMethod.discountedFee : shippingMethod.feePerCase;
  32. const shippingCost = priceData.quantity * shippingPerCase;
  33. return priceData.basePrice - priceData.discount + shippingCost;
  34. }

拆分循环

what

将一个循环拆分成多个循环

where

当遇到一个身兼数职的循环时可以将循环拆解,让一个循环只做一件事情, 那就能确保每次修改时你只需要理解要修改的那块代码的行为就可以了。该行为可能会被质疑,因为它会迫使你执行两次甚至多次循环,实际情况是,即使处理的列表数据更多一些,循环本身也很少成为性能瓶颈,更何况拆分出循环来通常还使一些更强大的优化手段变得可能。

how

  1. // ==================重构前==================
  2. const people = [
  3. { age: 20, salary: 10000 },
  4. { age: 21, salary: 15000 },
  5. { age: 22, salary: 18000 }
  6. ]
  7. let youngest = people[0] ? people[0].age : Infinity;
  8. let totalSalary = 0;
  9. for (const p of people) {
  10. // 查找最年轻的人员
  11. if (p.age < youngest) youngest = p.age;
  12. // 计算总薪水
  13. totalSalary += p.salary;
  14. }
  15. console.log(`youngestAge: ${youngest}, totalSalary: ${totalSalary}`);
  16. // ==================重构后==================
  17. const people = [
  18. { age: 20, salary: 10000 },
  19. { age: 21, salary: 15000 },
  20. { age: 22, salary: 18000 }
  21. ]
  22. let totalSalary = 0;
  23. for (const p of people) {
  24. // 只计算总薪资
  25. totalSalary += p.salary;
  26. }
  27. let youngest = people[0] ? people[0].age : Infinity;
  28. for (const p of people) {
  29. // 只查找最年轻的人员
  30. if (p.age < youngest) youngest = p.age;
  31. }
  32. console.log(`youngestAge: ${youngest}, totalSalary: ${totalSalary}`);
  33. // ==================提炼函数==================
  34. const people = [
  35. { age: 20, salary: 10000 },
  36. { age: 21, salary: 15000 },
  37. { age: 22, salary: 18000 }
  38. ]
  39. console.log(`youngestAge: ${youngestAge()}, totalSalary: ${totalSalary()}`);
  40. function totalSalary() {
  41. let totalSalary = 0;
  42. for (const p of people) {
  43. totalSalary += p.salary;
  44. }
  45. return totalSalary;
  46. }
  47. function youngestAge() {
  48. let youngest = people[0] ? people[0].age : Infinity;
  49. for (const p of people) {
  50. if (p.age < youngest) youngest = p.age;
  51. }
  52. return youngest;
  53. }
  54. // ==================使用工具类进一步优化==================
  55. const people = [
  56. { age: 20, salary: 10000 },
  57. { age: 21, salary: 15000 },
  58. { age: 22, salary: 18000 }
  59. ]
  60. console.log(`youngestAge: ${youngestAge()}, totalSalary: ${totalSalary()}`);
  61. function totalSalary() {
  62. return people.reduce((total,p) => total + p.salary, 0);
  63. }
  64. function youngestAge() {
  65. return Math.min(...people.map(p => p.age));
  66. }

拆分变量

what

将一个变量拆分成两个或多个变量

where

如果变量承担多个责任, 它就应该被替换为多个变量, 每个变量只承担一个责任。

how

  1. // ==================重构前==================
  2. let temp = 2 * (height + width);
  3. console.log(temp);
  4. temp = height * width;
  5. console.log(temp);
  6. // ==================重构后==================
  7. const perimeter = 2 * (height + width);
  8. console.log(perimeter);
  9. const area = height * width;
  10. console.log(area);

分解条件表达式

what

将条件表达式提炼成函数

where

在带有复杂条件逻辑的函数中,往往可以将原函数中对应的代码改为调用新函数。

对于条件逻辑, 将每个分支条件分解成新函数可以带来的好处:

  • 提高可读性
  • 可以突出条件逻辑, 更清楚地表明每个分支的作用
  • 突出每个分支的原因

how

  1. // ==================重构前==================
  2. // 计算一件商品的总价,该商品在冬季和夏季的单价是不同的
  3. if (!aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd))
  4. charge = quantity * plan.summerRate;
  5. else
  6. charge = quantity * plan.regularRate + plan.regularServiceCharge;
  7. // ==================重构后==================
  8. if (summer())
  9. charge = summerCharge();
  10. else
  11. charge = regularCharge();
  12. function summer() {
  13. return !aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd);
  14. }
  15. function summerCharge() {
  16. return quantity * plan.summerRate;
  17. }
  18. function regularCharge() {
  19. return quantity * plan.regularRate + plan.regularServiceCharge;
  20. }
  21. // 进一步优化(使用三元运算符)
  22. charge = summer() ? summerCharge() : regularCharge();
  23. function summer() {
  24. return !aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd);
  25. }
  26. function summerCharge() {
  27. return quantity * plan.summerRate;
  28. }
  29. function regularCharge() {
  30. return quantity * plan.regularRate + plan.regularServiceCharge;
  31. }

合并条件表达式

what

将多个条件表达式合并

where

当发现这样一串条件检查: 检查条件各不相同, 最终行为却一致。 如果发现这种情况,就应该使用“逻辑或”和“逻辑与”将它们合并为一个条件表达式。

how

  1. // ==================重构前==================
  2. if (anEmployee.seniority < 2) return 0;
  3. if (anEmployee.monthsDisabled > 12) return 0;
  4. if (anEmployee.isPartTime) return 0;
  5. // ==================重构后==================
  6. if (isNotEligableForDisability()) return 0;
  7. function isNotEligableForDisability() {
  8. return ((anEmployee.seniority < 2)
  9. || (anEmployee.monthsDisabled > 12)
  10. || (anEmployee.isPartTime));
  11. }

以卫语句取代嵌套条件表达式

what

如果某个条件极其罕见,就应该单独检查该条件,并在该条件为真时立刻从函数中返回。 这样的单独检查常常被称为“卫语句”(guard clauses)。

where

如果使用if-else结构,你对if分支和else分支的重视是同等的。这样的代码结构传递给阅读者的消息就是:各个分支有同样的重要性。卫语句就不同了,它告诉阅读者: “这种情况不是本函数的核心逻辑所关心的, 如果它真发生了,请做一些必要的整理工作,然后退出。” 为了传递这种信息可以使用卫语句替换嵌套结构。

how

  1. // ==================重构前==================
  2. function payAmount(employee) {
  3. let result;
  4. if(employee.isSeparated) {
  5. result = {amount: 0, reasonCode:"SEP"};
  6. }
  7. else {
  8. if (employee.isRetired) {
  9. result = {amount: 0, reasonCode: "RET"};
  10. }
  11. else {
  12. result = someFinalComputation();
  13. }
  14. }
  15. return result;
  16. }
  17. // ==================重构后==================
  18. function payAmount(employee) {
  19. if (employee.isSeparated) return {amount: 0, reasonCode: "SEP"};
  20. if (employee.isRetired) return {amount: 0, reasonCode: "RET"};
  21. return someFinalComputation();
  22. }

将查询函数和修改函数分离

what

将查询动作从修改动作中分离出来的方式

where

如果遇到一个“既有返回值又有副作用”的函数,此时可以将查询动作从修改动作中分离出来。

how

  1. // ==================重构前==================
  2. function alertForMiscreant (people) {
  3. for (const p of people) {
  4. if (p === "Don") {
  5. setOffAlarms();
  6. return "Don";
  7. }
  8. if (p === "John") {
  9. setOffAlarms();
  10. return "John";}
  11. }
  12. return "";
  13. }
  14. // 调用方
  15. const found = alertForMiscreant(people);
  16. // ==================重构后==================
  17. function findMiscreant (people) {
  18. for (const p of people) {
  19. if (p === "Don") {
  20. return "Don";
  21. }
  22. if (p === "John") {
  23. return "John";
  24. }
  25. }
  26. return "";
  27. }
  28. function alertForMiscreant (people) {
  29. if (findMiscreant(people) !== "") setOffAlarms();
  30. }
  31. // 调用方
  32. const found = findMiscreant(people);
  33. alertForMiscreant(people);

以上就是JavaScript代码优化技巧示例详解的详细内容,更多关于JavaScript优化技巧的资料请关注w3xue其它相关文章!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号