C# public static List<string> GeneratePhoneNumber(int number) { Random rand = new Random(); List<string> str_phone = new List<string>(); string phoneNumber = "1"; // 手机号第一位为 1 for (int i = 0; i < number; i++) { for (int i = 0; i < 7; i++) { phoneNumber += rand.Next(0, 10).ToString(); // 生成随机数 } phoneNumber = phoneNumber.Insert(4, "****"); // 格式 str_phone.Add(phoneNumber); } return str_phone; }优化代码
时间: 2024-02-14 20:18:31 浏览: 100
在循环生成电话号码时,每次生成后都要将其插入到列表中,这样会导致频繁的内存分配和复制操作,影响性能。可以改为在循环内部先生成所有的电话号码,再一次性添加到列表中,代码如下:
```
public static List<string> GeneratePhoneNumber(int number)
{
Random rand = new Random();
List<string> str_phone = new List<string>(number); // 预分配空间
for (int i = 0; i < number; i++)
{
string phoneNumber = "1";
for (int j = 0; j < 7; j++) // 修改循环变量名
{
phoneNumber += rand.Next(0, 10).ToString();
}
phoneNumber = phoneNumber.Insert(4, "****");
str_phone.Add(phoneNumber);
}
return str_phone;
}
```
另外,如果需要生成的号码数量比较大,可以考虑使用StringBuilder来拼接字符串,减少内存分配和复制操作。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![dll](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)