Skip to content

Commit 9efb6ca

Browse files
stepanchegfacebook-github-bot
authored andcommitted
Add some explanations for isinstance()
Reviewed By: JakobDegen Differential Revision: D63813312 fbshipit-source-id: 93c09649fbe8af3dc2f90764f3114785e92bcfa0
1 parent 4d71985 commit 9efb6ca

File tree

1 file changed

+15
-0
lines changed
  • starlark/src/values/typing/type_compiled

1 file changed

+15
-0
lines changed

starlark/src/values/typing/type_compiled/globals.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,21 @@ pub(crate) fn register_eval_type(globals: &mut GlobalsBuilder) {
3636
}
3737

3838
/// Check if a value matches the given type.
39+
///
40+
/// This operation can be very fast or very slow depending on how it is used.
41+
///
42+
/// `isinstance(x, list)` is very fast,
43+
/// because it is compiled to a special bytecode instruction.
44+
///
45+
/// `isinstance(x, list[str])` is `O(N)` operation
46+
/// because it checks every element in this list.
47+
///
48+
/// `L = list; [isinstance(x, L) for x in y]` is slow when `L` is not a constant:
49+
/// `isinstance()` first converts `list` to a type in a loop, which is slow.
50+
///
51+
/// But last operation can be optimized like this:
52+
/// `L = eval_type(list); [isinstance(x, L) for x in y]`:
53+
/// `eval_type()` converts `list` value into prepared type matcher.
3954
fn isinstance<'v>(
4055
#[starlark(require = pos)] value: Value<'v>,
4156
#[starlark(require = pos)] ty: ValueOfUnchecked<'v, AbstractType>,

0 commit comments

Comments
 (0)