# 巧用取模实现轮询效果

{% embed url="<https://v.douyin.com/r8RNXRu/>" %}

{% embed url="<https://www.bilibili.com/video/BV1V94y127fF/>" %}

前两天啊

copilot给我提示出来这样一句代码

我觉得挺有意思

就是这个

什么意思呢

原本啊我是想这样写

加加然后呢判断一下

如果他大于等于length让他等于

意思就是让这个

index 啊

在这个历史的里面做一个顺序的循环

比如012到这之后呢再

但是他这个写法呢也可以

什么意思

就是

先加

这个没问题

然后加1之后呢

拿这个结果再去取模这个长度

也就是说当他加到

这个长度的时候

一取模就回到0了

当然了严格来说

这样写的效率一定是不如下边这样的

因为这块每次都要做一个取模计算

但下边这种写法呢

他大部分情况只是做了一个比较

不过啊我还是做了下测试

这么写的话

1,000万次的循环呢

他会多花30毫秒左右

所以呢从这个时间上来看

我觉得啊

绝大部分项目

可以不用考虑他的效率问题

所以不知道如果让大家选择的话

大家更倾向于使用哪种方法


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sunzsh.gitbook.io/xiaoshan.bug/qiao-yong-qu-mo-shi-xian-lun-xun-xiao-guo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
