循环遍历二维数组的最快方法? [英] Fastest way to loop through a 2d array?

查看:552
本文介绍了循环遍历二维数组的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是偶然发现了此博客文章.作者展示了两个代码示例,这些示例通过一个矩形循环并计算出一些东西(我想这是计算代码只是一个占位符).在其中一个示例中,他垂直扫描矩形,而在另一个水平方向.然后他说第二个是最快的,每个程序员都应该知道为什么.现在我一定不能成为程序员,因为在我看来,它完全一样.有人可以向我解释吗?

I just stumbled upon this blog post. The author shows two code samples that loop through a rectangle and compute something (my guess is the computing code is just a placeholder). On one of the example, he scans the rectangle vertically, and on the other horizontally. He then says the second is fastest, and every programmer should know why. Now I must not be a programmer, because to me it looks exactly the same. Can anyone explain that one to me?

谢谢.

推荐答案

缓存一致性.当水平扫描时,数据在内存中的位置会更靠近,因此缓存未命中的次数会减少,因此性能会更快.对于足够小的矩形,这无关紧要.

Cache coherence. When you scan horizontally, your data will be closer together in memory, so you will have less cache misses and thus performance will be faster. For a small enough rectangle, this won't matter.

这篇关于循环遍历二维数组的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆