The predict2() function initializes the SVM only on first call which improves performance significantly. But it still needs to build the model from scratch.
If the training takes a comparatively long time or the training data cannot be provided along with the code, this is a problem.
R has the ability to serialize objects to disk and read them back with saveRDS() and readRDS().
Having saved the SVM object like that, we can restore it from disk instead of rebuilding it each time.
Let's run this statement three times again:
select s.*, r_predict3(s.*) from generate_series(1,1000) s;
484 ms for the first run. 302 ms for each of the following two. Average: 363 ms.
That's a 75% improvement compared to the original code.
Still, the first call is more expensive than the subsequent ones.
Can we do better?