kdb: Where phrase AND performance

kdb: Where phrase AND performance

KX reference 说 #1 应该比 #2 快。

q)select from t where c2>15,c3<3.0
q)select from t where (c2>15) and c3<3.0

In the first example, only c3 values corresponding to c2 values greater than 15 are tested.

In the second example, all c2 values are compared to 15, and all c3 values are compared to 3.0. The two result vectors are ANDed together.

---

但是,我注意到在下面的示例中情况恰恰相反。我错过了什么吗?

N:100000000;
t:([]a:N?1000;b:N?1000;c:N?1000)
\t select from t where a>500,b>500;        / ~500ms
\t select from t where (a>500) and b>500;  / ~390ms

这是一个笼统的说法 - 当他们说 should 更快时,他们的意思是在大多数实际情况下。总会有一些边缘情况,其中某些方法不会根据数据的形状更快。

在您的情况下,由于第一个过滤器没有大量减少数据集(而是减半),因此在第二个过滤器之前将第二列“减半”的开销恰好大于直接将第二个过滤器应用于整个第二列(毕竟 kdb 在矢量运算方面非常快)。

例如,如果您的第一个过滤器将数据集减少了很多,那么您会看到更多的速度提升,因为第二个过滤器应用于较小集的开销减少更为显着:

q)\t select from t where a<10,b>500;
263
q)\t select from t where (a<10) and b>500;
450

q)\t select from t where a=950,b>500;
208
q)\t select from t where (a=950) and b>500;
422

如果第一列应用了属性,比如 `g#(内存中)或 `p#(磁盘上),速度提升会更加明显。由于在大多数大批量生产场景中都会有属性加速第一个过滤器,他们声明它应该更快(几乎暗示如果不是那么你可能没有使用属性!)。

这是一个极端示例,其中 a 列具有排序属性:

q)`a xasc `t;
q)\t select from t where a=950,b>500;
1
q)\t select from t where (a=950) and b>500;
428