Skip to content

Commit

Permalink
Normalize index in Vector.at in builtin method
Browse files Browse the repository at this point in the history
The main culprit of a Vector slowdown (when compared to Array) was the
normalization of the index when accessing the elements.
Turns out that the Graal was very persistent on **not** inlining that
particular fragment and that was degrading the results in benchmarks.

Being unable to force it to do it (looks like a combination of thunk
execution and another layer of indirection) we resorted to just moving
the normalization to the builtin method. That makes Array and Vector
perform roughly the same.
  • Loading branch information
hubertp committed Oct 19, 2022
1 parent 28daf14 commit e147277
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,7 @@ type Vector a
[1, 2, 3].at -1 == 3
at : Integer -> Any ! Index_Out_Of_Bounds_Error
at self index =
actual_index = if index < 0 then self.length + index else index
Panic.catch Invalid_Array_Index_Error_Data (self.unsafe_at actual_index) _->
Panic.catch Invalid_Array_Index_Error_Data (self.at_builtin index) _->
Error.throw (Index_Out_Of_Bounds_Error_Data index self.length)

## ADVANCED
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package org.enso.interpreter.node.expression.builtin.immutable;

import com.oracle.truffle.api.interop.InteropLibrary;
import com.oracle.truffle.api.interop.InvalidArrayIndexException;
import com.oracle.truffle.api.interop.UnsupportedMessageException;
import com.oracle.truffle.api.nodes.Node;
import org.enso.interpreter.dsl.BuiltinMethod;
import org.enso.interpreter.node.expression.builtin.interop.syntax.HostValueToEnsoNode;
import org.enso.interpreter.runtime.Context;
import org.enso.interpreter.runtime.data.Vector;
import org.enso.interpreter.runtime.error.PanicException;

@BuiltinMethod(
type = "Vector",
name = "at_builtin",
description = "Returns an element of Vector at the specified index.")
public class AtVectorNode extends Node {
private @Child InteropLibrary interop = InteropLibrary.getFactory().createDispatched(3);
private @Child HostValueToEnsoNode toEnso = HostValueToEnsoNode.build();

Object execute(Vector self, long index) {
try {
long actualIndex = index < 0 ? index + self.length(interop) : index;
return self.readArrayElement(actualIndex, interop, toEnso);
} catch (InvalidArrayIndexException e) {
Context ctx = Context.get(this);
throw new PanicException(
ctx.getBuiltins().error().makeInvalidArrayIndexError(self, index), this);
} catch (UnsupportedMessageException e) {
throw new PanicException(e.getMessage(), this);
}
}
}

0 comments on commit e147277

Please sign in to comment.