声明与表达式
const index = 1
let intNum = 1;
intNum = 1.1; // 该变量在声明时为整型数据,建议后续不要赋值浮点型数据
let doubleNum = 1.1;
doubleNum = 1; // 该变量在声明时为浮点型数据,建议后续不要赋值整型数据
class Time {
static start: number = 0;
static info: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
}
function getNum(num: number): number {
let total: number = 348;
const info = Time.info[num - Time.start]; // 从循环中提取不变量
for (let index: number = 0x8000; index > 0x8; index >>= 1) {
if ((info & index) != 0) {
total++;
}
}
return total;
}
函数
let arr = [0, 1, 2];
function foo(array: number[]): number {
return array[0] + array[1];
}
foo(arr);
- 避免使用可选参数,可选参数可为undefined,函数内部使用该参数,需要进行非空值的判断,造成额外开销,可以考虑默认参数
// 可选参数
function add(left?: number, right?: number): number | undefined {
if (left != undefined && right != undefined) {
return left + right;
}
return undefined;
}
// 默认参数
function add(left: number = 0, right: number = 0): number {
return left + right;
}
数组
- 如果涉及纯数字计算场景,推荐使用TypedArray数据结构
const typedArray1 = new Int8Array([1, 2, 3]);
const typedArray2 = new Int8Array([4, 5, 6]);
let res = new Int8Array(3);
for (let i = 0; i < 3; i++) {
res[i] = typedArray1[i] + typedArray2[i];
}
- 避免使用联合类型数据的数组,将相同类型的数据放置在同一数组中
// 优化前
let arrNum: number[] = [1, 1.1, 2]; // 数值数组中混合使用整型数据和浮点型数据
let arrUnion: (number | string)[] = [1, 'hello']; // 联合类型数组
// 优化后
let arrInt: number[] = [1, 2, 3];
let arrDouble: number[] = [0.1, 0.2, 0.3];
let arrString: string[] = ['hello', 'world'];
异常
- 避免频繁抛出异常,因为创建异常时回构造异常的栈帧,造成性能的损耗
// 优化前
function div(a: number, b: number): number {
if (a <= 0 || b <= 0) {
throw new Error('Invalid numbers.')
}
return a / b
}
function sum(num: number): number {
let sum = 0
try {
for (let t = 1; t < 100; t++) {
sum += div(t, num)
}
} catch (e) {
console.log(e.message)
}
return sum
}
// 优化后
function div(a: number, b: number): number {
if (a <= 0 || b <= 0) {
return NaN
}
return a / b
}
function sum(num: number): number {
let sum = 0
for (let t = 1; t < 100; t++) {
if (t <= 0 || num <= 0) {
console.log('Invalid numbers.')
}
sum += div(t, num)
}
return sum
}